尝试更改每个 div 的背景颜色并使其在鼠标悬停在 div 上时保持原样。不能让它改变颜色。我究竟做错了什么? Here's the fiddle.
$('.container').on('hover', '#gridSquare', function(){
$(this).css('background-color', 'white');
});
提前致谢!
最佳答案
无需使用 jQuery,只需使用 css 选择器 :hover
#gridSquare:hover {
background-color: white;
}
演示:Fiddle
如果要使用jQuery,需要使用mouseenter和mouseleave
$('.container').on('mouseenter', '#gridSquare', function () {
$(this).css('background-color', 'white');
}).on('mouseleave', '#gridSquare', function () {
$(this).css('background-color', '');
});
演示:Fiddle
更新
正如下面评论中所建议的,元素的 ID 在文档中必须是唯一的,因此使用 class 而不是 id 来对相似的元素进行分组。
演示:Fiddle
关于javascript - 悬停时更改div颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581875/