[英]Execute two divs in same javascript
我正在尝试同时在两个不同的div类中进行淡入淡出效果。 为此,我需要两个不同的脚本,并为两个div执行相同的脚本,因此会滞后。 有什么办法可以在同一脚本中执行两个div,例如(.fadein,.fadeo)? FIDDLE- jsfiddle.net/562am/ 。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script> //Function 1
$(function(){
$('.fadeo img:gt(0)').hide();
setInterval(function(){$('.fadeo :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadeo');}, 2000);
});
</script>
<script> //Function 2
$(function(){
$('.fadein img:gt(0)').hide();
setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 2000);
});
</script>
这是将两者合并为1函数的意思吗?
$(function(){
var classes = ['.fadeo', '.fadein'];
$.each(classes, function (index, elem){
var selectorToHide = elem + ' img:gt(0)',
selectorToFadeOut = elem + ' :first-child';
$(selectorToHide).hide();
setInterval(function() {
$(selectorToFadeOut)
.fadeOut()
.next('img')
.fadeIn()
.end()
.appendTo(elem);
},
2000);
});
});
2 setInterval自行运行-它们可能会产生滞后。 正确的方法是使用1个间隔并在那里执行整个逻辑。
使用appendTo,您每2秒更改一次DOM。 此方法会导致额外的性能问题,并导致应用程序运行缓慢。 我建议您保留当前图像的索引,并根据需要进行更改(如下所示)。
在我的示例中,我计算了最小图像数(如果单独的div具有不同的图像数)。
$(function () {
// a value can be fixed - a constant
var imagesCount = Math.min($('.fadeo > img').size(),
$('.fadein > img').size());
var i = 0;
display(i);
setInterval(function () {
i = (i+1) % imagesCount;
display(i);
}, 2000);
});
function display(nth) {
$('.fadeo > img').hide().eq(nth).show();
$('.fadein > img').hide().eq(nth).show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.