我对jquery有点陌生,我有一个工作函数,可以在列表元素的悬停时交换图像。 我试图添加一个fadeOut和fadeIn,但它不工作。图像淡出,但它没有得到新图像的正确路径。这是工作脚本。
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').attr('src', path + newimage)
});
});
这是我为淡入效果所做的尝试 (还有一些变体,没有一个能成功):
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $('.menu-child').attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$('.swap > img').attr('src', path + newimage).fadenIn();
});
});
});
HTML:
<section class="submenuWrapper">
<ul class="twinsub">
<li class="twinmultisub twinleft">
<ul>
<li class="menu-child" data-path="menu-interior"><a href="#"><span>Interior Painting</span></a></li>
<li class="menu-child" data-path="menu-exterior"><a href="#"><span>Exterior Painting</span></a></li>
</ul>
</li>
<li class="twinmultisub twinimg">
<section class="swap">
<img src="images/menu-exterior.jpg" />
</section>
</li>
</ul>
</section>
我们有几件事情。
试试这个。
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
$('.swap > img').fadeOut(function() {
$(this).attr('src', path + newimage).fadeIn();
});
});
});
工作实例: https:/jsfiddle.netsabrickfudLgqxs3。
你现在大概可以自己找出它的工作原理了,但如果你想了解更多细节,请告诉我。
以下是一个带有适当注释的示例
$(document).ready(function() {
var path = 'images/';
$('.menu-child').hover(function() {
var newimage = $(this).attr('data-path') + '.jpg';
if(newimage != (path + $('.swap > img').attr('src'))){
/*if the current image being displayed is not the same
as the data-path of the hovered element.
This prevents it from running even when the image should
not be changing
*/
$('.swap > img').fadeOut(0);
//first fade out the current image
$('.swap > img').attr('src', path + newimage);
//then change the path when it is not visible
$('.swap > img').fadeIn(500);
//then fade in the new image with the new path
}
});
});