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

时间:2014-01-23 14:25:03

标签: javascript jquery html css

我有以下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/

谢谢!

3 个答案:

答案 0 :(得分: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);
        });
    });
});

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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

Date.prototype.addHours = function(h){
    this.setHours(this.getHours()+h);
    return this;
}

this.setState((prevState) => {
  return {time: prevState.time.addHours(12) }
});
.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;
}

相关问题