【问题标题】:How to change an img src on a parent div hover?如何在父 div 悬停时更改 img src?
【发布时间】:2016-08-18 20:19:28
【问题描述】:

我遇到了一个问题,图像在使用 jQuery 的 div 悬停时没有改变。除图像外,其他所有内容都会相应更改。目前,蓝色图像保持不变,不会改变。我还注意到悬停时绿色图像显示不合适,这很奇怪。我做错了什么?

我在这里创建了一个 jsfiddle 问题:https://jsfiddle.net/8bcfnd6f/

HTML:

<div id="widget">
    <div id="text-button-widget">
        <h2>Lorem Ipsum</h2>
        <img id="widget-img" src="http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png"/>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
     </div>
</div>

CSS:

#widget:hover {
    cursor: pointer;
    background-color: #0098db;
}

jQuery:

$('#widget').hover(function(){ // hover in
    $('#widget h2, #widget p').css('color','#fff');
    $('#widget-img').css('background', 'url("http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif") no-repeat center center fixed');
}, function(){ // hover out
    $('#text-button-widget h2').css('color','#000');
    $('#text-button-widget p').css('color','#000');
    $('#widget-img').css('background', 'url("http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png") no-repeat center center fixed');
});

【问题讨论】:

  • 我认为问题在于您有一个带有图像的图像元素,并且您正在更改背景,因此图像元素仍然存在。
  • 无需 JS 即可轻松完成。 jsfiddle.net/8bcfnd6f/1

标签: jquery html css hover src


【解决方案1】:

现在,您的代码不会更改 src,它只是更改背景并将其添加到当前 src。 如果你只需要改变src,你应该使用这样的代码:

    $('#widget').hover(function(){ // hover in
    $('#widget h2, #widget p').css('color','#fff');
    $('#widget-img').attr("src", "http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif");
}, function(){ // hover out
    $('#text-button-widget h2').css('color','#000');
    $('#text-button-widget p').css('color','#000');
    $('#widget-img').attr("src", "http://www.clipartbest.com/cliparts/di8/KRL/di8KRL8ie.png");
});

【讨论】:

    【解决方案2】:
    $('#widget-img').attr('src', 'http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif')
    

    【讨论】:

      【解决方案3】:

      如果您完全想更改&lt;img&gt;,您应该将其宽度和高度设置为0,并相应地添加填充。然后添加背景图片。

      CSS 解决方案,根据您的情况。无需 Javascript。

      #widget:hover {
        cursor: pointer;
        background-color: #0098db;
        color: #fff;
      }
      #widget:hover img {
        height: 0;
        width: 0;
        background: url("http://www.clipartkid.com/images/17/youtube-play-icon-clipart-Ns7Pf4-clipart.gif") no-repeat;
        background-size: 256px 256px;
        background-position: center center;
        padding: 128px;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-22
        • 2016-08-07
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 2020-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多