2013-03-08 117 views
6

我在列表中有几个项目,要突出一个用户通过应用一些CSS样式点击,可能是背景颜色等如何使用jquery突出显示选定的列表项目?

我的HTML看起来像这样:

<ul class="thumbnails"> 
    <li> 
     <a href="#" class="thumbnail"> 
      <img class="giftthumb" src='thumb1.jpg' alt=""> 
      <span class="gifttitle">Thumb1</span> 
     </a>  
    </li> 
    <li> 
     <a href="#" class="thumbnail"> 
      <img class="giftthumb" src='thumb2.jpg' alt=""> 
      <span class="gifttitle">Thumb3</span> 
     </a>  
    </li> 
    <li> 
     <a href="#" class="thumbnail"> 
      <img class="giftthumb" src='thumb3.jpg' alt=""> 
      <span class="gifttitle">Thumb3</span> 
     </a>  
    </li> 
</ul> 

了jQuery检索所选项目:

$('.thumbnail').click(function(e) { 
    e.preventDefault(); 

    ??? 

}) 

回答

14

你可以使用jQuery的class management methods(即在这种情况下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 Demo

这比直接从jQuery的/ JavaScript的改变CSS属性(与.css()方法例如)一个更好的解决方案,因为问题的分离将使您的代码更易于管理和可读。

+0

我从来没有见过类似这样的语法给函数分配一个变量......(例如$ thumbs =) – Paul 2013-03-08 19:15:09

+2

@Paul我添加了一些注释来解释这个移动。 '$ thumbs'基本上会保存'$('。thumbnail')'的结果,因为在jQuery中大多数方法会返回jQuery集合以允许链接。我这样做是因为在点击处理程序中,我不必再为'.thumbnail'元素查询DOM,我已经拥有了它们。如果元素正在改变(我的意思是增加/删除),所以不是静态的,这个方法不会被使用,你应该再次查询DOM。 – kapa 2013-03-08 19:18:33

+0

非常好,谢谢你的信息。我总是在这个网站学习:) – Paul 2013-03-08 19:35:11

1
$('.thumbnail').click(function(e) { 
    e.preventDefault(); 
    $(this).css('background-color', 'red'); 
}) 
1

你???将是:

$('.thumbnail').removeClass('selected'); 
$(this).addClass('selected'); 

然后,你所要做的就是定义你的'选定'CSS类。

1

如果需要积极持续这里有一个CSS方式:

li:focus{ 
 
    background: red; 
 
} 
 
li:active{ 
 
    background: gold; 
 
}
<ul> 
 
    <li tabindex="1">Item 1</li> 
 
    <li tabindex="1">Item 2</li> 
 
    <li tabindex="1">Item 3</li> 
 
</ul> 
 

 
Now click <b>here</b> and see why it's not persistent.
在某些情况下

以上可能是有用的 - 只突出显示当前“点击活动”项目&hellip;

相关问题