Немного предыстории моей проблемы:.hover() кажется перезаписать .click()
Я делаю доску на основе игры, когда пользователь собирается быть в состоянии сделать путь от квадрата к другое, дело в том, что при щелчке квадрата он должен оставаться подсвеченным независимо от того, находится ли указатель над ним, а затем покидает его. Кажется, что когда квадрат щелкнут, а затем указатель оставляет его, обработчикIn .hover() изменяет состояние атрибута типа пути, позволяя квадрату быть несмещенным, когда указатель входит и покидает квадрат.
это то, что у меня до сих пор:
$(function() {
\t $('td.soccer-field').click(function(){
\t \t \t if ($('#dice1').text() != '' && $('#dice2').text() != '') {
\t \t \t \t if ($("[path-type='begin-path']").length == 0) {
\t \t \t \t \t $(this).attr('path-type','begin-path');
\t \t \t \t } else if ($("[path-type='begin-path']").length && $(this).attr('path-type') != 'end-path'){
\t \t \t \t \t $(this).attr('path-type','end-path');
\t \t \t \t \t $('[path-type="selecting-actual-path"]').attr('path-type','actual-path');
\t \t \t \t } else if ($(this).attr('path-type') == 'end-path'){
\t \t \t \t \t $(this).attr('path-type','');
\t \t \t \t };
\t \t \t }
\t \t });
\t $('td.soccer-field').hover(
\t \t function() {
\t \t \t if ($('#dice1').text() != '' && $('#dice2').text() != '') {
\t \t \t \t if ($("[path-type='begin-path']").length == 0) {
\t \t \t \t \t $(this).attr('path-type','select-begin-path');
\t \t \t \t } else if ($(this).attr('path-type') == ''){
\t \t \t \t \t var actualCell = $(this).attr('id') + $(this).parent().attr('id');
\t \t \t \t \t var cell, distance,dicesResult = parseInt($('#dice1').text())+ parseInt($('#dice2').text());
\t \t \t \t \t $("[path-type*='path']").each(function () {
\t \t \t \t \t \t cell = $(this).attr('id') + $(this).parent().attr('id');
\t \t \t \t \t \t distance = new Board().calculateDistanceSquares(actualCell,cell);
\t \t \t \t \t \t if (distance == 1 && $("[path-type='selecting-actual-path']").length < (dicesResult -2))
\t \t \t \t \t \t {
\t \t \t \t \t \t \t \t $(this).attr('path-type','selecting-actual-path');
\t \t \t \t \t \t \t \t return false;
\t \t \t \t \t \t }
\t \t \t \t \t });
\t \t \t \t } \t
\t \t \t };
\t \t },function() {
\t \t \t if ($(this).attr('path-type') == 'selecting-actual-path' || $(this).attr('path-type') == 'select-begin-path') {
\t \t \t \t \t $(this).attr('path-type','');
\t \t \t }
\t \t });
\t $('#diceRoller').click(function() {
\t \t $('#dice1').text(Math.floor(Math.random()*6)+1);
\t \t $('#dice2').text(Math.floor(Math.random()*6)+1);
\t \t $(this).attr('disabled',true);
\t });
});
//function Board(playerTurn, piecesPosition, gamePhase, gameBegginingType, container)
function Board(){
\t this.buildBoard = function (container) {
\t \t var board = $('<table></table>').attr('id','board');
\t \t var row, cell,containerHeight,containerWidth;
\t \t for (var i=0; i<10; i++){
\t \t \t row = $('<tr></tr>').attr('id',i+1);
\t \t \t for (var j=0; j<20; j++){
\t \t \t \t cell = $('<td></td>');
\t \t \t \t cell.attr('path-type','');
\t \t \t \t if ((j == 0 || j == 19) && (i >= 3) && (i <= 6)) {
\t \t \t \t \t cell.addClass('behind-goal');
\t \t \t \t }
\t \t \t \t else if ((j > 0) && (j < 19)){
\t \t \t \t \t cell.attr('id',String.fromCharCode(j+96));
\t \t \t \t \t cell.addClass("soccer-field");
\t \t \t \t };
\t \t \t \t row.append(cell);
\t \t \t }
\t \t \t board.append(row);
\t \t }
\t \t $('#'+container).append(board);
\t };
\t this.calculateHorizontalDistance = function (sq1,sq2) {
\t \t var column1 = sq1.substring(0,1).charCodeAt(0);
\t \t var column2 = sq2.substring(0,1).charCodeAt(0);
\t \t return (Math.abs(column1-column2));
\t };
\t this.calculateVerticalDistance = function (sq1, sq2) {
\t \t var row1 = parseInt(sq1.substring(1));
\t \t var row2 = parseInt(sq1.substring(1));
\t \t return (Math.abs(row1-row2));
\t };
\t this.calculateDistanceSquares = function(sq1, sq2){
\t \t return(this.calculateVerticalDistance(sq1,sq2)+this.calculateHorizontalDistance(sq1,sq2));
\t }
}
var board = new Board();
\t board.buildBoard('left');
#left table{
\t width: 60em;
\t height: 25em;
\t border:0.2em solid black;
\t border-collapse:collapse;
}
#left table tr{
\t height: 2.5em;
\t
}
#left table tr td{
\t width: 3.33em;
}
td.soccer-field{
\t border: 0.1em solid black;
}
td.behind-goal{
\t background-color: #F8FAB4;
}
td[path-type*="path"]{
\t border: 0.15em solid #F8FAB4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boardContainer">
\t <div id="right">
\t \t <p id="dice1"></p><p id="dice2"></p>
\t \t <button id="diceRoller">Lanzar Dados</button>
\t </div>
\t
\t <div id="left"></div>
</div>
\t
Небольшая помощь будет очень признателен
Просто использовать 2 различных классов. Один, который вы включаете/выключаете, когда плитка наводится, и другой, который используется, когда выбран плит. – enhzflep
Это именно то, что я собирался сказать. –
Кроме того, вы можете захотеть просмотреть псевдоселектор ': hover'. В принципе, это означает, что вам не нужно ничего делать, чтобы изменить внешний вид при зависании, за исключением добавления правила css для нужного элемента (ов). Это лучше, чем переключать класс вкл/выкл всякий раз, когда мышь входит/выходит из элемента. – enhzflep