我环顾四周找到了解决方案,但我想知道是否有办法编写更简单的代码。基本上我创建的是一个简单的淡入淡出,淡出图像的悬停效果。
$(document).on('mouseenter','.photos div',function () {
"use strict";
$(this).find('img.nocolor').stop().animate({ 'opacity': '0' }, 800);
});
$(document).on('mouseleave','.photos div',function () {
"use strict";
$(this).find('img.nocolor').stop().animate({ 'opacity': '1' }, 800);
});
我知道你可以将mouseenter,mouseleave放在一起,但我不知道如何构建这样的切换功能。请让我知道如何简化这一点。
答案 0 :(得分:5)
你想用Javacscript实现这个效果吗?您可以使用纯CSS完全实现您的目标:
#an-image {
opacity: 0.2;
transition: opacity 0.8s linear;
}
#an-image:hover {
opacity: 1;
transition: opacity 0.8s linear;
}
您可以在此处查看一个有效的示例:http://jsfiddle.net/oqqx1z3k/
您可以查看this example以查看它与您提供的示例相结合。
答案 1 :(得分:4)
我没有对此进行测试,但我相信您可以使用.fadetoggle()函数来完成您想要的操作。
$('.photos div').on('mouseenter mouseleave',function () {
$(this).find('img.nocolor').togglefade('slow');
});
或
$('.photos div').on({
mouseenter: function() {
$(this).find('img.nocolor').stop().animate({ 'opacity': '0' }, 800);
},
mouseleave: function() {
$(this).find('img.nocolor').stop().animate({ 'opacity': '1' }, 800);
}
})
然而,我不喜欢使用切换和mouseenter和mouseleave,因为这些功能基于鼠标移动而不是基于html文档的位置。
答案 2 :(得分:1)
您可以使用event.type
$(document).on('mouseenter mouseleave','.photos div',function (evt) {
"use strict";
var opacity = evt.type === 'mouseenter' ? 0 : 1;
$(this).find('img.nocolor').stop().animate({ 'opacity': opacity }, 800);
});
fadeTo()
方法也与您正在使用的动画相同
$(document).on('mouseenter mouseleave','.photos div',function (evt) {
"use strict";
var opacity = evt.type === 'mouseenter' ? 0 : 1;
$(this).find('img.nocolor').stop().fadeTo( 800, opacity);
});
答案 3 :(得分:0)
$( '.photos div' ).hover(
function() {
// MOUSE ENTER
$(this).find('img.nocolor').stop().animate({ 'opacity': '0' }, 800);
}, function() {
// MOUSE LEAVE
$(this).find('img.nocolor').stop().animate({ 'opacity': '1' }, 800);
}
);
编辑:绑定功能的选择器不是文档,它是' .photos div'
答案 4 :(得分:0)
您可以使用event.type
通过单个切换功能实现此目的,如下所示:
function toggleAnimation(eventName)
{
"use strict";
$(document).find('img.nocolor').stop().animate({ 'opacity':
(eventName == 'mouseenter') ? '0' : '1' }, 800);
}
$(document).ready(function(){
$(document).on('mouseenter mouseleave','.photos div',function (event) {
toggleAnimation(event.type);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="photos">
<div>
<img width="300px" src="http://www.lb.undp.org/content/dam/lebanon/img/AboutLebanon/Lebanon.png" class="nocolor" />
</div>
</div>