jquery - 在链接的鼠标悬停时更改 div 的背景图像

标签 jquery html background-image

我想要实现的目标

我希望 div 的背景图像在鼠标悬停在所述 div 内的链接上时发生变化。

例子

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

我尝试过的

我试过使用 jQuery 交换背景图像:

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

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

</script>

任何人都可以告诉我我缺少什么吗?

解决方案

<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)
"); 
}).mouseleave(function(){
jQuery('#container').css("background-image", "url(http://thumbs.dreamstime.com/thumblarge_536/12838649102C1cO5.jpg)"); 
});
</script>

最佳答案

缺少 id=

<div id="container">

不是

<div="container">

并且还按照链接所述将 .click() 与 .hover() 切换

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>

关于jquery - 在链接的鼠标悬停时更改 div 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7375175/

相关文章:

javascript - 无需按下即可触发 keyup

javascript - 无法使用 javascript/jquery 获得正确的时间格式

JQuery 在三态图标/按钮中识别当前的 CSS 背景图像?

css 3D过渡图像

javascript - 使用 angularjs 路由多个 html 文件

html - 多个背景相互叠加(正常、拉伸(stretch)、正常)

jquery - 如何在 <a 标签上使用 $(document).on("click..?

jquery - 如何让SlideUp停在一定高度

javascript - HTML5多图选择限制及编辑

html - Vue - 输入多个复选框