2015-02-23 45 views
0

我想知道如何使用jQuery将图像源更改为使用html数据属性进行悬停时使用fadeout/fadeIn效果的第二个图像。如何使用HTML5数据属性在悬停时添加淡入/淡出?

它应该是这样的:

  1. 悬停,第一个图像淡出。
  2. 来自data-alt-src的第二个图像被淡入。
  3. 在鼠标移出时,它会从原始src淡出回到第一幅图像。

这里是我迄今为止在DOM:

<img class="myimageclass" src="http://www.example.com/path-to/picture.jpg" data-alt-src="http://www.example.com/path-to/picture-alt.jpg" alt="my picture"> 

的最佳方式任何建议,以实现这一点?

编辑:这里是JavaScript的我到目前为止,我已经能够得到交换的形象,但我卡住在激发淡入/淡出方法:

$(document).ready(function() { 
     var sourceSwap = function() { 
     var $this = $(this); 
     var newSource = $this.data('alt-src'); 
     $this.data('alt-src', $this.attr('src')); 
     $this.attr('src', newSource); 
} 

$(function() { 
    $('img.myimgclass').hover(sourceSwap, sourceSwap); 
    }); 
}); 
+1

有你到目前为止尝试过什么? – 2015-02-23 17:42:34

+0

你可能想看看hoverintent插件http://cherne.net/brian/resources/jquery.hoverIntent.html。默认的jQuery悬停处理程序有一些反应问题。 – 2015-02-23 17:44:58

+0

我刚刚编辑了我的问题,并添加了我正在使用的JavaScript! – jaworrom 2015-02-23 18:39:53

回答

1
$(".myimageclass").hover(function() { 

    $(this).fadeOut(2000); 
    setTimeout(function() { 
     var temp = this.getAttribute("data-src"); 
     this.setAttribute("data-src", this.src); 
     this.src = temp; 
     $(this).fadeIn(2000); 
    }, 2000); 

}, 

function() { 
    $(this).fadeOut(2000); 
    setTimeout(function() { 
     var temp = this.getAttribute("data-src"); 
     this.setAttribute("data-src", this.src); 
     this.src = temp; 
     $(this).fadeIn(2000); 
    }, 2000); 
}); 
+0

感谢您的回应!我实现了你的代码片段,但我遇到了一些问题。我得到以下错误: '未捕获的TypeError:无法读取未定义的属性'src' 这是行5和16('var temp = this.dataset.src;') – jaworrom 2015-02-23 18:36:05

+0

查看更新的代码。 – void 2015-02-23 18:47:11

+0

很高兴帮助,请考虑投票并将其标记为正确答案。 – void 2015-02-23 22:17:09

相关问题