2011-11-14 45 views
0

我想让我的星级评估人员保持我使用的精灵的背景位置,当点击一个容器div内的5个表列之一。在鼠标悬停时,我添加了一个样式属性来做到这一点,但是当我点击并添加一个具有相同CSS的类时,它不会影响背景位置。我默认添加了这个类,但它仍然不起作用。我想这实际上是一个比其他任何问题更多的CSS问题。如何添加类。处理鼠标悬停,但不是点击

这里是我使用的代码:http://jsfiddle.net/cbYCZ/3/

任何帮助是极大的赞赏。这对我来说是一个真正的面条划痕。

+1

你能上传你的明星形象服务器不需要认证? – ExpExc

+0

我改变了图像从另一台服务器拉。它现在应该工作。对于那个很抱歉。 –

回答

3

你有这样的规则:

#rating 
{ 
    background: ...; 
} 

然后将此规则:

.star3 
{ 
    background: ...; 
} 

。这都是被同时应用于同一个元素,但由于CSS Specificity,一个用一个id (#rating)正在重写带有类(.star3)的那个,因此添加.class3对呈现的页面上的任何内容都没有任何影响。

更改.star3#rating.star3修复问题:http://jsfiddle.net/gLTSz/

+0

谢谢谢谢谢谢谢谢! –

0

由于您的图片资源(已删除的图片路径)需要验证,因此很难确切地看到发生了什么。

不过,我可以看到,你是不是真的使用jQuery API,因为它的目的是:

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

添加和移除风格有.css()

用于添加和删除值有.val()

对于鼠标悬停/鼠标移开有.hover()

我会开始改变这些,看看问题是否存在。否则,你就需要把星星图像地方公有的,因此我们可以看到在行动代码

+0

谢谢,我会给它一个镜头。同时,如果您想立即看到它,我已经修复了这个图片。对于那个很抱歉。 –

1

你刚才添加的id来td没有到div

刚看到这个Demo

希望它可以帮助。

+0

这就是我原来的样子,但它仍然不起作用 –

0

这里是一个解决方案,是很多比你的jQuery更简洁。你可能会发现它以一种实用的方式教会了许多更先进的技术。

我已经相当广泛地评论了代码。如果您有任何问题,请告诉我。

请注意,我的解决方案依赖于@Abhi Beckert的关键观察,因此他应该获得Accepted Answer荣誉。

的代码是在这里: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')); 
});