【问题标题】:Replacing background image using jQuery not working [duplicate]使用jQuery替换背景图像不起作用[重复]
【发布时间】:2015-01-04 13:33:35
【问题描述】:

我创建了一个父 div。在那个 div 里面有多个子 div:第一个是背景图片,第二个是网站名称,第三个是一些文本。

使用 jQuery,当用户将鼠标悬停在第二个 div 即网站名称 div 上时,第三个 div 即文本 div 是可见的。

现在我想要的是,当文本 div 变得可见时,也替换第一个 div 中的图像。到目前为止,这是我的 HTML 和 jQuery 代码:

HTML:

<div class="layer-3" style="opacity: 1;">
        <a href="#">
            <div class="contentImg3">{Div holding the image as a background}</div>

            <div class="contentBlock3" style="opacity: 1;">
                <span class="btn-block">
                    <span class="help-block webHdln">Website Name</span>
                </span>
            </div>

            <div class="contentText3">text Div</div>
        </a>                
        </div>
        <!-- .layer-2 ENDS -->

JS:

$(".contentBlock3").mouseenter(function () {
        $('.contentText3').fadeIn(1500);
        $('.contentImg').css("background-image", "images/gurus_bw.jpg)");
        $('.contentImg').css("background-position", "top 30px)");
    });

CSS 行不工作...我做错了什么?

【问题讨论】:

  • 除了现有答案中提到的点之外,看不到任何带有class="contentImg" 的元素。
  • 您的 HTML 代码是 W3C 验证的噩梦。您不能在链接标签内放置块元素!您应该用 div 替换这些链接。我这样做的方法是在您的 .contentImg 元素上交换 CSS 类。我会在你的 css 样式表中定义一个普通的背景图像:.contentImg3 { background: url("image/url") no-repeat center center;} 并指定另一个类,例如,swapImg,具有不同的背景图像。然后在 JS 方面,只需在 mouseenter 上执行 $('.contentImg3').addClass('swapImg'); 和在 mouseleave 上执行 $('.contentImg3').removeClass('swapImg');
  • 感谢 @Marventus 为您提供替换课程的解决方案......它工作得很好......

标签: javascript jquery html css


【解决方案1】:

改变

$('.contentImg').css("background-image", "images/gurus_bw.jpg)"); // miss: url(..

$('.contentImg').css("background-image", "url(images/gurus_bw.jpg)");  

读取 CSS background-image 属性

【讨论】:

  • 我也尝试添加网址,但没有成功...
  • 在jsfiddle上添加示例
猜你喜欢
  • 2017-04-29
  • 2018-03-22
  • 2016-03-23
  • 2018-03-25
  • 1970-01-01
  • 2018-06-23
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多