2011-11-14 44 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')); 
});