连续图像仅在最后一次消失后出现在悬停时

时间:2016-11-12 23:21:30

标签: javascript jquery html

在我的一个小项目中,我有几个按钮,当它们悬停时会在另一个div中显示一个图像。在悬停第一个按钮后,当悬停第二个按钮时,第一个图像仍然存在并且两个图像都显示出来。

我对第二张图片做什么只出现在第一张图片后才消失?

我的JavaScript代码:

$(".button").hover(function () {
    var iN = $(this).attr("id").charAt(6);
    $('#img'+ iN).fadeIn('slow');
},function() {
    var iN = $(this).attr("id").charAt(6);
   $('#img' + iN).fadeOut('slow');
});

3 个答案:

答案 0 :(得分:0)

我就是这样做的,但它可能不适用于您的用例。 (如果没有,请在您的问题中添加更多详细信息。)

请注意,该示例使用jQuery“starts with”选择器:^=重新隐藏ID以字母img开头的所有元素

$('img').hide();

$(".button").hover(function () {
    var iN = $(this).attr("id").charAt(6);
    $('#img'+ iN).fadeIn('slow');
},function() {
    $('[id^=img]').fadeOut();
});
div{height:100px;width:200px;border:1px solid orange;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="123456f" class="button">
  <img id="imgf" src="http://placeimg.com/200/100/nature" />
</div>
<div id="kittenc" class="button">
  <img id="imgc" src="http://placeimg.com/200/100/animals" />
</div>

答案 1 :(得分:0)

此解决方案对我很有用。希望它有所帮助:)。

$(document).ready(function(){
  $(".button").hover(function(){
    var buttonID = $(this).attr("id");
     $("#image").attr('src', 'images/pic'+ buttonID+".jpg");  
  });
}); 
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id = "container">
<button id = "1" class = "button">Button1</button>
<button id = "2" class = "button">Button2</button>
<button id = "3" class = "button">Button3</button>
<button id = "4" class = "button">Button4</button>
</div>

<img id = "image" src="">

答案 2 :(得分:0)

在这个片段中,我们是:

  • 使用事件mouseentermouseleave
  • 使用toggleClass()来控制opacity的{​​{1}}。
  • 使用<img>确定按钮触发的鼠标事件,以确定按钮的位置。
  • 使用index()将关联的img与按钮的索引位置相匹配。
  • .eq() s的渐变转换效果由CSS属性<img>opacity完成,这些属性绑定到类transition.on

&#13;
&#13;
.off
&#13;
$('button').on('mouseenter mouseleave', function() {
  var position = $(this).index();
  $('#gallery').find('img').eq(position).toggleClass('on off');
});
&#13;
body {
  background: #CCC;
}
#gallery {
  margin: 0 auto;
}
fieldset {
  display: inline-block;
}
img.off {
  opacity: 0;
  transition: opacity .5s linear;
}
img.on {
  opacity: 1;
  transition: opacity .5s linear;
}
img:first-of-type {
  margin-left: 17px;
}
button {
  width: 75px;
  line-height: 1.2;
  font-size: 14px;
  padding: 2px 5px;
  border: 3px outset grey;
  color: 0ee;
  cursor: pointer;
}
&#13;
&#13;
&#13;