单击div时更改图像src

时间:2015-06-28 16:05:47

标签: jquery html image

我有imagediv

<img class="img-responisve pull-left" id="thumb" src="color/40252_mercury_palette_490x437.jpg"/>
<div class="thumbnail color a" style="background-image:url(color/40292_charcoal_palette_230x128.jpg)"></div>

当我点击div时,带有image的{​​{1}}应更改为div id="thumb"中的image更大一点。 这是我尝试过的,但它不起作用:

background

3 个答案:

答案 0 :(得分:1)

正如Frederic Nault所说,$(this).attr("src")无法获取图片路径,您应该使用.css()

如下所示

$(".a").click(function(){
    var r1 = $(this).css('background-image').slice(4,-1).replace("230x128.","490x437.");
    $('#thumb').attr("src", r1);
});

答案 1 :(得分:0)

你应该参考div的background-image

$("div.a").click(function(){
    var r1 = $(this).css("background-image").replace('url(','').replace(')','').replace("230x128.","490x437.");
    $('#thumb').attr("src", r1);
});

答案 2 :(得分:0)

查看以下代码

$('div.a').click(function(){
  $('img.img-responisve').attr("src", $(this).css('background-image').replace('url(','').replace(')',''));
});
img.img-responisve {
  width: 300px;
  height: auto;
  display: block;
  float: left;
  }

div.a {
  width: 180px;
  height: 180px;
  background-image: url('http://i.cdn.turner.com/v5cache/CARTOON/site/Images/i80/tj_tom_180x180.png');
  border: 1px solid #000;
  display: block;
  float: left;
  cursor: pointer;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="img-responisve pull-left" id="thumb" src="http://img1.wikia.nocookie.net/__cb20150128155039/disney/images/f/f3/Baby_Tom-29.png"/>
<div class="thumbnail color a"></div>