我有一个社交图标列表,当悬停在上面时会增加宽度以显示更多内容,而其余的会减小宽度以保持整体 ul 宽度相同。我想知道是否有人可以告诉我我的做法是否好,或者是否有更好的做法。我仍在努力学习 jquery 及其最佳实践。
此外,除了最后一个列表项偶尔会掉落之外,一切似乎都运行良好。我认为这与悬停元素宽度的增加速度与其他元素的减少速度不同有关。
这是我所拥有的(注意目前只有 facebook 有与之关联的内容):
$(function() {
$('.social-container > li').on({
mouseenter: function () {
$('.social-container > li').stop().animate({'width':'16%'},400);
$(this).stop().animate({'width':'50%'},400).queue(function(){
$(this).find(".icon-placeholder").hide();
$(this).find(".icon-link").stop().fadeIn("slow").show();
$(this).dequeue();
});
},
mouseleave: function () {
$('.social-container > li').stop().animate({'width':'25%'},400);
$(this).stop().animate({'width':'25%'},400);
$(this).find(".icon-link").stop().fadeOut("slow").hide();
$(this).find(".icon-placeholder").show();
}
});
});
最佳答案
https://jsfiddle.net/uuwdr5Ly/4/
你最好使用一些 css 动画而不是 jquery - 现在这很有可能。
我对你的代码做了什么?
.icon-link{
opacity: 0;
position: absolute;
不幸的是,您不能为从 display: none
到 display: block
的元素设置动画 - 因此您可以将不透明度设置为 0 并设置绝对位置来隐藏它。
ul.social-container:hover li{
width: 16%;
}
ul.social-container li:hover {
width: 50%;
}
在这里,您可以设置鼠标悬停时如何调整社交大小的方式。在 mouseout 时,它们将获得 25% 的基本宽度。无需编写 .on('mouseover')
!
ul.social-container, ul.social-container li {
transition: width .4s ease;
}
ul.social-container .icon-placeholder,
ul.social-container .icon-link {
transition: opacity .4s ease;
}
这就是您可以在这些元素上定义过渡的方式。始终选择您实际要更改的一个 Prop ,以节省一些内存。
ul.social-container li:hover .icon-placeholder {
opacity: 0;
}
ul.social-container li:hover .icon-link {
opacity: 1;
display: inline;
}
这就是您隐藏-显示图标内容的方式!
GL!
附言不要忘记 IE8 已死,但您仍然需要所有这些前缀(-ms、-moz、-webkit)。
关于javascript - 关于编写 jquery 动画的更好方法的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632496/