简体   繁体   English

用属性值更改背景图像

[英]Change background-image with attribute value

I have this link: 我有这个链接:

<div class="wp-show-posts-inner" data-src="http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg"></div>

I need to change background-image url from another class with data-url on hover event. 我需要在悬停事件中使用data-url从另一个类更改background-image url。 I try this right now but doesn't work: 我现在尝试此操作,但不起作用:

var bg_img = jQuery('.wp-show-posts-inner').attr('data-src');    
jQuery('.wp-show-posts-inner').on('mouseover',function() {    
  jQuery('.home-banner .bg').css({'background-image': "url('"+bg_img+"')"});
});

This script get me this result: 这个脚本给我这个结果:

element.style {
  background-image: url((unknown));
}

i need this: 我需要这个:

<div class="bg" style="background-image: url(http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg);"></div>

any advice? 有什么建议吗? thanks 谢谢

Your syntax is wrong for getting attr data-src, use this 您的语法对于获取attr data-src是错误的,请使用此

 var bg_img = jQuery('.wp-show-posts-inner').attr('data-src'); jQuery('.wp-show-posts-inner').on('mouseover',function() { jQuery('.home-banner .bg').css({'background-image': "url('"+bg_img+"')"}); }); jQuery('.wp-show-posts-inner').on('mouseleave',function() { jQuery('.home-banner .bg').css({'background-image': "url()"}); }); 
 .bg{height:100px;width:100px;} .wp-show-posts-inner{height:100px;width:100px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="home-banner"> <div class="bg"> </div> </div> <div class="wp-show-posts-inner" data-src="http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg">wp-show-posts-inner (Hover on me)</div> 

You code has three problem. 您的代码有三个问题。

  1. You should use selector before using .attr() . 您应该在使用.attr()之前使用选择器。 So use $(this).attr('data-src') 所以使用$(this).attr('data-src')

  2. In end of second parameter of .css() there is additional ' that should removed .css()的第二个参数末尾,应删除其他'

  3. css background-image property should wrapped into url() css background-image属性应该包装在url()

So you code should change to 所以你的代码应该改为

$('.wp-show-posts-inner').hover(function() {    
    $('.home-banner .bg').css('background-image', "url("+$(this).attr('data-src')+")");
}); 

 $('.wp-show-posts-inner').hover(function() { $('.home-banner .bg').css('background-image', "url("+$(this).attr('data-src')+")"); }); 
 .bg { width: 100px; height: 100px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wp-show-posts-inner" data-src="http://maria138.coroleu.com/wp-content/uploads/2018/09/foto1.jpg">wp-show-posts-inner</div> <div class="home-banner"> <div class="bg">bg</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM