开发者

Change background image of div on mouseover of a link

What I want to achieve

I want the background image of div to change on the mouseover of a link within the said div.

Example

<div id="container">
     <a href="" id="linktomouseover"></a>
</div>

What I've tried

I've tried swapping the background image using jQuery:

<script language="javascript" type="text/javascript">

jQuery('#linktomouseover').mouseover(function()
{
jQuery('#container').css("background-image", "url(bg-b.png)");
});

</script>

Can anyone advise me on what I'm missing?

Solution

<style> 
#container{ 
width:100%; 
height:100%; 
background-image:url(http://thumbs.dreamstime.com/thumblarge_536/12838649102C1cO5.jpg); 
} 
</style> 

<div id="container"><br><br> 
<a href="" id="linktomouseover">hover</a> 
</div>

<script> 
jQuery('#linktomouseover').hover(function() 
{ 
jQuery('#container').css("background-image", 
"url(http://static4.depositphotos.com/1011237/285/i/450/dep_2853473-B开发者_StackOverflow中文版ackground-for-your-web-store.jpg)
"); 
}).mouseleave(function(){
jQuery('#container').css("background-image", "url(http://thumbs.dreamstime.com/thumblarge_536/12838649102C1cO5.jpg)"); 
});
</script>


missing id=

<div id="container">

not

<div="container">

and also switch .click() with .hover() as link says

http://sandbox.phpcode.eu/g/31e7b/6

<style> 
#container{ 
        width:100%; 
    height:100%; 
    background-image:url(http://thumbs.dreamstime.com/thumblarge_536/12838649102C1cO5.jpg); 
} 
</style> 
<div id="container"><br><br> 
     <a href="" id="linktomouseover">hover</a> 
</div> 
<script> 
jQuery('#linktomouseover').hover(function() 
{ 
    jQuery('#container').css("background-image", "url(http://static4.depositphotos.com/1011237/285/i/450/dep_2853473-Background-for-your-web-store.jpg)"); 
}); 
</script>


This might not be the solution, but you are currently not running your code after the dom-model is loaded, which probably means that jQuery('#linktomouseover') returns nothing.

Try this:

<script>
jQuery(function() {
    // Your code here
});
</script>

Also, if you would like to have this effect for more than one link, you can do it like this;

html:

<div class="container">
    <a class="linktomouseover">link</a>
</div>
<div class="container">
    <a class="linktomouseover">link</a>
</div>

js:

jQuery(function() {
    jQuery('.linktomouseover').mouseover(function() {
        jQuery(this).parent().css('background-image', "url('bg-b.png')");
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜