div css在悬停时没有变化

时间:2015-10-12 01:50:27

标签: javascript jquery css

当我将鼠标悬停在它们上面时,我想要更改一个div网格。我尝试制作它,使背景颜色变为白色,当鼠标不再悬停在背景颜色上时,返回灰色。我一直在寻找,我似乎无法找到解决我所寻找的问题的答案。

var d = ("<div class='square'></div>");
var value = [];


function createGrid(numSquares) {
    var area = $('#g_area');
    var squareSize = Math.floor(area.innerWidth() /numSquares);
    var n =0;
    for (var i = 0, len = (numSquares*numSquares); i < len; i++) {
        area.append(d);
        for (var j = 0; j < numSquares; j++) {
            $(d).attr('id', n);
            n++;
            value[n] = 0;
        }
    }


    $('.square').height(squareSize);
    $('.square').width(squareSize);
};

function resetGrid() {
    $(".square").remove();
}

$(document).ready(function () {
    createGrid(32);

});

$('.square').hover(function() {
    $(this).css({backgroundColor: '#FFFFFF'}) ;
    $(this).css({backgroundColor: '#C8C8C8'}) ;
});

jsfiddle:https://jsfiddle.net/psyonix/1g9p59bx/16/

3 个答案:

答案 0 :(得分:5)

您的悬停语法不正确,您需要传递两个函数:

$('.square').hover(function () {
    $(this).css({
        backgroundColor: '#FFFFFF'
    });}, function(){
    $(this).css({
        backgroundColor: '#C8C8C8'
    });
});

<强> jsFiddle example

答案 1 :(得分:1)

您需要定义handlerOut。 这应该工作。 https://jsfiddle.net/1g9p59bx/18/

$('.square').hover(function () {
    $(this).css({
        backgroundColor: '#FFFFFF'
    });
}, function() {
    $(this).css({
        backgroundColor: '#C8C8C8'
    });
});

答案 2 :(得分:0)

为什么不把它放在你的CSS上?

.square:hover
{
    background-color: #FFFFFF;
}