在另一个div上盘旋时更改主div的src

时间:2015-11-16 06:14:08

标签: javascript jquery css3 imagesource

<html>
<head><script src="jquery-1.10.1.min.js"></script></head>
<body>
<div><img src="images/img-40.jpg" class="Main-image"/></div>

<div id="iranimg"><img src="images/irani.jpg" style="display:none;"/>Iran </div>
<div id="spainimg"><img src="images/spanin.jpg" style="display:none;"/>Spain </div>
<div id="turkeyimg"><img src="images/turkey.jpg" style="display:none;"/>Turkey </div>



<script>

$(document).ready(function(){
$('#iranimg').hover(function() {
$( '.Main-image' ).attr("src","images/irani.jpg");
}, function() {
    $( '.Main-image' ).attr("src","images/img-40.jpg");

});


})
</script>

</body>
</html>

我想只在悬停在那个div上时更改另一个div的src of 'main-image' div with a src。

当我将鼠标悬停在该div上时,它会替换为特定的src

我想动态获取每个div的src并将其替换为主要div图像的src

4 个答案:

答案 0 :(得分:0)

在悬停时获取内部src标记的img并将其替换为

$('#iranimg,#spainimg,#turkeyimg').hover(function() {
  $('.Main-image').attr("src", $('img',this).attr('src'));
}, function() {
  $('.Main-image').attr("src", "images/img-40.jpg");
});

仅供参考:使用class代替id,这样您就可以更简单了

<强> jQuery的:

$('.imgChange').hover(function() {
  $('.Main-image').attr("src", $('img',this).attr('src'));
}, function() {
  $('.Main-image').attr("src", "images/img-40.jpg");
});

<强> HTML:

<div><img src="images/img-40.jpg" class="Main-image"/></div>

<div class="imgChange"><img src="images/irani.jpg" style="display:none;"/>Iran </div>
<div class="imgChange"><img src="images/spanin.jpg" style="display:none;"/>Spain </div>
<div class="imgChange"><img src="images/turkey.jpg" style="display:none;"/>Turkey </div>

答案 1 :(得分:0)

尝试:

   $('div[id$="img"]').hover(function() {
    $( '.Main-image' ).attr("src",$(this).find('img').attr('src'));
    }, function() {
    $( '.Main-image' ).attr("src","images/img-40.jpg");

    });

答案 2 :(得分:0)

你的意思是:

如果您要预先加载图像,可以保留图像,但使用数据属性和类将事件添加到所有div

&#13;
&#13;
$(function() {
  $('.countries').hover(function() {
    $('.Main-image').attr("src", $(this).data("src"));
  }, function() {
    $('.Main-image').attr("src", "images/img-40.jpg");
  });
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <img src="images/img-40.jpg" class="Main-image" />
</div>

<div class="countries" id="iranimg" data-src="images/irani.jpg">Iran</div>
<div class="countries" id="spainimg" data-src="images/spanin.jpg">Spain</div>
<div class="countries" id="turkeyimg" data-src="images/turkey.jpg">Turkey</div>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

 $('#iranimg').hover(function() {
    $('.Main-image').attr('src', $(this).find('img').attr('src'));
 }, function() {
    $('.Main-image').attr('src', "images/img-40.jpg");
 });