首先,我是js/jquery的新手。我有一个可以在页面中修改和添加的列表,该页面由:<ol id="elementlist"></ol>定义
在页面加载时,它是一个空列表。使用JQuery将列表项追加到它的后面。
我希望能够将鼠标悬停在每个元素上并更改颜色。我已经使用JQuery提供的on()函数完成了这项工作:
// highlight on mouseover
$("#elementlist").on("mouseover", "li", function(){
$(this).css("background-color","#f2fdf2");
});
// restore white background
$("#elementlist").on("mouseout", "li", function(){
$(this).css("background-color","#ffffff");
});我还希望能够双击安莉,将其突出显示,并使其保持突出显示。这也应该禁止在将鼠标悬停在该元素上时更改颜色。我可以双击并更改颜色,但不能使用以下代码禁用悬停处理程序:
// highlights on double click, but doesn't disable mouseover/mouseout
$("#elementlist").on("dblclick", "li", function(){
$(this).css("background-color","#f2d2d2");
$(this).off("mouseover", "");
$(this).off("mouseout", "");
});我不能仅禁用已单击的特定列表项(其他列表项应该仍然可以突出显示)。任何帮助都将不胜感激。
发布于 2013-06-20 06:20:52
使用data()或类来设置突出显示的状态,并进行检查:
$("#elementlist").on({
mouseenter: function(){
if (!$(this).hasClass('highlight')) $(this).css("background-color","#f2fdf2");
},
mouseleave: function() {
if (!$(this).hasClass('highlight')) $(this).css("background-color","#fff");
},
dblclick: function() {
$(this).css("background-color","#f2d2d2").addClass('highlight');
}
}, 'li');您也可以使用CSS来完成大部分操作:
#elementlist li {background-color : #f2fdf2}
#elementlist li:hover {background-color : #fff}
#elementlist li.highlight, #elementlist li.highlight:hover {background-color : f2d2d2}只需保留点击处理程序
$("#elementlist").on('dblclick', 'li', function() {
$(this).addClass('highlight');
});发布于 2013-06-20 06:22:47
该事件绑定到父ol,对li使用off()没有任何效果,因为它们没有绑定事件。
一种解决方案是将事件绑定到没有disabledhover类的li。然后双击添加这样的类。
// highlight on mouseover
$("#elementlist").on("mouseover", "li:not(.disabledhover)", function(){
$(this).css("background-color","#f2fdf2");
});
// restore white background
$("#elementlist").on("mouseout", "li:not(.disabledhover)", function(){
$(this).css("background-color","#ffffff");
});
// highlights on double click, but doesn't disable mouseover/mouseout
$("#elementlist").on("dblclick", "li", function(){
$(this).css("background-color","#f2d2d2");
$(this).addClass("disabledhover");
});。
发布于 2013-06-20 06:16:27
您的侦听器位于'#elementList‘元素上,这就是off()不起作用的原因。
http://jsfiddle.net/blackjim/HShzg/1/
$("li", "#elementlist")
.on("mouseover", function(){
// highlight on mouseover
$(this).css("background-color","#f2fdf2");
})
.on("mouseout", function(){
// restore white background
$(this).css("background-color","#ffffff");
})
.on("dblclick", function(){
// highlights on double click, but doesn't disable mouseover/mouseout
$(this).css("background-color","#f2d2d2");
$(this).off();
});PS:如果你的列表有很多元素,那么这么多的监听器可能不是一个好主意,你应该考虑一个'flag‘的方式来打开/关闭绑定,就像@nnnnnn所说的那样。
https://stackoverflow.com/questions/17202277
复制相似问题