如何添加class.工作在鼠标上,但不是在点击



我试图让我的星级保持我使用的精灵的背景位置,当点击容器div内的5个表列之一。在鼠标上方,我添加了一个样式属性来做到这一点,这是有效的,但是当我点击并添加一个类与相同的css在它不影响背景位置。我在默认情况下添加了这个类,但它仍然不起作用。我想这确实是一个css问题。

下面是我使用的代码:http://jsfiddle.net/cbYCZ/3/

非常感谢任何帮助。

你有这样的规则:

#rating 
{
   background: ...;
}

然后这个规则:

.star3
{
   background: ...;
}

这两个都被同时应用于同一元素,但由于CSS特异性,具有id (#rating)的一个覆盖了具有类(.star3)的一个,因此添加.class3对渲染页面没有任何影响。

.star3更改为#rating.star3解决问题:http://jsfiddle.net/gLTSz/

您只需将id添加到td而不是div

看看这个Demo

希望有帮助。

很难看到到底发生了什么,因为您的图像资源(已删除的图像路径)需要身份验证。

然而,我可以看到你并没有真正使用jQuery api,因为它是预期的:

对于删除类,您应该使用.removeClass()

添加和删除样式有.css()

添加和删除值有.val()

对于mouseover/mouseout,有.hover()

我会从改变这些开始,看看问题是否仍然存在。否则,你需要把星星的图像放在公共的地方,这样我们就可以看到你的代码

这是一个比jQuery简洁得多的解决方案。你会发现它以实用的方式教会了你很多更高级的技术。

我对代码进行了相当广泛的注释。如果你有任何问题,请告诉我。

请注意,我的解决方案依赖于@Abhi Beckert的关键观察,所以他应该得到接受答案的荣誉。

代码如下:http://jsfiddle.net/GtPnr/4/

这里是新的HTML:

<div id="rating">
    <table>
        <tr>
            <td><div id="1star" data-stars="1"></div></td>
            <td><div id="2star" data-stars="2"></div></td>
            <td><div id="3star" data-stars="3"></div></td>
            <td><div id="4star" data-stars="4"></div></td>
            <td><div id="5star" data-stars="5"></div></td>
        </tr>
    </table>
</div>
<input type="hidden" id="stars" />

和我的简洁,但注释,Javascript:

// store re-used jQuery objects in variables to greatly improve performance.
// this avoids re-creating the same jQuery object every time it is used.
var $rating = $('#rating');
var $starsField = $('#stars');
// use the .hover() as a shortcut for 'mouseover' and 'mouseout' handlers.
$rating.find('td').hover(function() {
    // remove all star classes then dynamically construct class name to add
    // using the data method to retrieve the value stored in the "data-stars" attribute
    // I added.
    $rating.removeClass('star1 star2 star3 star4 star5').addClass('star' + $(this).find('div').first().data('stars'));
}, function() {
    // this is the mouse-out handler. Remove all star classes
    $rating.removeClass('star1 star2 star3 star4 star5');
    // if the current value in the hidden field is set, then assign the correct class
    // so the star's clicked value is respected.
    var curVal = $starsField.val() || 0;
    if (curVal > 0) {
        $rating.addClass('star' + curVal);
    }
}).click(function() {
    // when clicking a star, store the value in the hidden input
    $starsField.val($(this).find('div').first().data('stars'));
});

最新更新