2010-09-17 242 views
2

我有几个div,我想为其生成css背景图像。他们会在盘旋时改变。是的,我知道我可以在css中轻松做到这一点,但它需要在jQuery中完成。jquery更改悬停的背景图像

代码:

$(document).ready(function() { 
    $('.hoverBox').css('background', 'url(img/box' + id + '.jpg)') 
    $('.hoverBox').hover(function(){ 
    $(this).css('background', 'url(img/box' + this.id + '_back.jpg)')      
    }, 
    function(){ 
    $(this).css('background', 'url(img/box' + this.id + '.jpg)')      
    }); 
}); 

HTML是这样的:

<div class="hoverBox" id="benefits"> 
content</div> 
<div class="hoverBox" id="installation"> 
content</div> 
<div class="hoverBox" id="shoponline"> 
content</div> 

这应该是很容易的,但我似乎无法使它工作。

援助将不胜感激! TIA。

+0

什么似乎是问题? – Reigel 2010-09-17 00:53:35

+0

我认为这是:'url(img/box'+ id +'.jpg)',但我无法弄清楚我要出错的地方。最初的背景图像不显示,当然,悬停图像也不显示。 – circey 2010-09-17 00:57:53

回答

0

什么是id?

它是在别处定义的一些神秘的变量还是你认为id会从选择器中读取是一种神奇的方式?

我猜你想用each()来得到id。

+3

太好了。感谢那 - 让它工作。讽刺是不必要的,但每个()都是我需要的。 – circey 2010-09-17 01:13:29

+0

如何更新代码或添加如何使用“each()”解决问题的示例?对于有同样问题的其他人(比如我^^)会有所帮助。 – ithil 2013-06-17 08:59:28