如何在鼠标离开具有HTML数据的另一个元素时淡出背景图像



当用户将鼠标悬停在锚点标记上时,我试图获得一种效果,这样父div将在特定背景中淡出(不同锚点的背景不同)。我得到的结果还可以,但并没有我希望的那么顺利。

以下是jsfiddle链接:https://jsfiddle.net/GJL2K/8cwcdthe/6/

这是Javascript:

$(function () {
$('.description').hide();
$('.page-right li a').on('mouseenter', function(event) {
// console.log(this);
event.stopPropagation();
var $background = "url('" + $(this).attr('data-background') + "')";
$(this).parents('.page-right')
.find('#back')
.stop()
.animate({opacity: .5}, 0)
.css({'background': $background})
.animate({opacity: .75}, 1000);
});
//    $('.page-right li a').on('mouseleave', function(event) {
//        $('.description').slideUp();
//        // console.log(this);
//        event.stopPropagation();
//                      
//        $(this).parents('.page-right').find('#back')
//            .stop
//            .animate({opacity: .5}, 0)
//            .css({'background': 'none'})
//            .animate({opacity: 1}, 1000, 'easeInQuad', 
//                function () {$('.description').slideUp();
//        });    
//    });
$('.page-right li a').on('click', function(event) {
event.preventDefault();
$(this).parent().next().slideToggle('fast');
});
});

问题是,当你将鼠标悬停在下一个链接上时,第一个背景会消失,下一个背景会跳到它的位置。最好在下一个背景淡入之前先淡出第一个背景,但正如您从注释的代码中看到的,我没有弄清楚mouseleave事件。

我看过其他代码,我想我可能走错了路。我更喜欢fadeOut/fadeIn效果,它似乎有更平滑的过渡,但我只看到它适用于两个背景图像,而不是我需要的所有图像。

如何使图像过渡更加平滑无缝?

使用您提供的内容,我能够在图像之间更流畅地设置动画。这是mouseenter处理程序:

$('.page-right li a').on('mouseenter', function(event) {
// console.log(this);
event.stopPropagation();
var $background = "url('" + $(this).attr('data-background') + "')";
var $element = $(this)
.parents('.page-right')
.find('#back')
.stop();
$element.fadeOut(500, function() {
$element
.css({'background': $background})
.fadeIn(500);
});
});

请注意,fadeOut调用使用回调来启动后台交换,然后启动相应的fadeIn。由于animate调用是异步的,以前的代码只是在动画过程中替换了背景,这就是为什么转换不平滑的原因。这要光滑得多。

工作jsFiddle可以在这里找到:https://jsfiddle.net/mgaskill/29tjauov/

当然,还可以进行额外的改进,尤其是预加载图像,这将是一个非常好的后续问题。

相关内容

最新更新