8

我在列表中有几个项目,并希望通过应用一些 CSS 样式(可能是背景颜色等)来突出显示用户单击的项目。

我的 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();

    ???

})
4

4 回答 4

16

您可以使用 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()例如使用方法)更好的解决方案,因为关注点分离将使您的代码更易于管理和可读。

于 2013-03-08T19:05:36.783 回答
2
$('.thumbnail').click(function(e) {
    e.preventDefault();
    $(this).css('background-color', 'red');
})
于 2013-03-08T19:03:08.053 回答
1

您的 ???将会:

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

然后你所要做的就是定义你的'selected' css 类。

于 2013-03-08T19:04:02.090 回答
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.

在某些情况下,上述内容可能很有用 - 仅突出显示当前的“点击活动”项目......

于 2017-01-26T01:36:04.233 回答