在鼠标悬停时淡入淡出图像......?

问题描述 投票:0回答:3

我有以下html和js。它从一个图像切换到另一个图像。但我希望这些图像能够淡入淡出(淡入淡出?这个术语是什么?)。我做了一次搜索但由于某种原因无法将其他淡入淡出方法调整到我的中。我怎么能做到这一点?

<li class="item">
    <a href="/link.html" class="gallery-item">
        <span>
            <img src="/pic1-1.jpg" data-hover="pic1-2.jpg" width="243" height="243" />
        </span>
    </a>   
</li>

以下Javascript

$(function () {
    $('.item img').each(function () {
        $(this).data('original', this.src)
    }).mouseenter(function () {
        $(this)
            .attr('src', $(this).data('hover'))
    }).mouseleave(function () {
        $(this)
            .attr('src', $(this).data('original'))
    })

})

这是一个小提琴:http://jsfiddle.net/9qGtv/52/

谢谢!

javascript jquery html css
3个回答
2
投票

http://jsfiddle.net/SuZQ8/

将您的JavaScript更改为此。如果你想让它们在没有暂停的情况下褪色,你会希望在DOM中存在两个图像,因为你不能淡化源的切换;

$(function () {
    $('.item img').each(function () {
        $(this).data('original', this.src);
    }).mouseenter(function () {
        $(this).fadeOut(500, function(){
            $(this).attr('src', $(this).data('hover'));
            $(this).fadeIn(500);
        });
    }).mouseleave(function () {
        $(this).fadeOut(500, function(){
            $(this).attr('src', $(this).data('original'));
            $(this).fadeIn(500);
        });
    });
});

0
投票

纯CSS

HTML:

<span class="imageContainer">
     <img src="/pic1-1.jpg" width="243" height="243"  class="staticimage" />
     <img src="/pic1-2.jpg" width="243" height="243"  class="hoverimage"/>
</span>

CSS:

.staticimage
{
  position:relative;
  left:0px;
  top:0px;
  transition:1s;
}

.hoverimage
{
  position:relative;
  left:0px;
  top:0px; 
  display:none;
  transition:1s;
}

.imageContainer:hover .staticimage
{
  display:none;
  transition:1s;
}

.imageContainer:hover .hoverimage
{
  display:inline-block;
  transition:1s;
}

0
投票

虽然问题已经有4年了,但我想我会添加我的解决方案。根据Mark的回答,这是我的方法:

.gallery-item {
  display: block;
  position: relative;
  width: 243px;
  height: 243px;
}

.staticimage,
.hoverimage {
  position: absolute;
  transition: all 0.4s linear;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-size: cover;
}

.hoverimage {
  opacity: 0;
}

.gallery-item:hover .hoverimage {
  opacity: 1;
}
<a href="/link.html" class="gallery-item">
  <div style="background-image: url('https://picsum.photos/250/?random')" class="staticimage"></div>
  <div style="background-image: url('https://picsum.photos/251/?random')" class="hoverimage"></div>
</a>
© www.soinside.com 2019 - 2024. All rights reserved.