如何使用jquery突出显示所选列表项?
我在列表中有几个项目,并希望通过应用一些CSS样式,可能是背景颜色等突出显示用户点击的项目。
我的HTML看起来像这样:
jQUery检索所选项目:
$('.thumbnail').click(function(e) { e.preventDefault(); ??? })
您可以使用jQuery的类管理方法 (在本例中为addClass()
和removeClass()
在所选项上添加一个类,并从所有其他项中删除相同的类(如果您只想一次选择一个)。
//save class name so it can be reused easily //if I want to change it, I have to change it one place var classHighlight = 'highlight'; //.click() will return the result of $('.thumbnail') //I save it for future reference so I don't have to query the DOM again var $thumbs = $('.thumbnail').click(function(e) { e.preventDefault(); //run removeClass on every element //if the elements are not static, you might want to rerun $('.thumbnail') //instead of the saved $thumbs $thumbs.removeClass(classHighlight); //add the class to the currently clicked element (this) $(this).addClass(classHighlight); });
然后在你的CSS中添加:
.highlight { background-color: cyan; font-weight: bold; }
jsFiddle演示
这是比直接从jQuery / Javascript更改CSS属性(例如使用.css()
方法)更好的解决方案,因为关注点的分离将使您的代码更易于管理和读取。
$('.thumbnail').click(function(e) { e.preventDefault(); $(this).css('background-color', 'red'); })
您的 ??? 将会:
$('.thumbnail').removeClass('selected'); $(this).addClass('selected');
然后,您所要做的就是定义您的“选定”css类。
如果你不需要active来持久化这里是一种CSS方式:
li:focus{ background: red; } li:active{ background: gold; }
- Item 1
- Item 2
- Item 3
Now click here and see why it's not persistent.