简体   繁体   English

在相同的javascript中执行两个div

[英]Execute two divs in same javascript

I'm trying fade effect in two different div classes at same same-time. 我正在尝试同时在两个不同的div类中进行淡入淡出效果。 For that i need two different scripts, and executing same script for two div(s), it lags. 为此,我需要两个不同的脚本,并为两个div执行相同的脚本,因此会滞后。 Is there any way to execute both divs in same script like (.fadein,.fadeo)? 有什么办法可以在同一脚本中执行两个div,例如(.fadein,.fadeo)? FIDDLE- jsfiddle.net/562am/ . 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>

Is this what you meant by combining the two into 1 function? 这是将两者合并为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 run on their own - they may produce lags. 2 setInterval自行运行-它们可能会产生滞后。 The correct way is to use 1 interval and do the whole logic there. 正确的方法是使用1个间隔并在那里执行整个逻辑。
With appendTo you're changing the DOM every 2 seconds. 使用appendTo,您每2秒更改一次DOM。 This method causes extra performance issues and leads to slower application run. 此方法会导致额外的性能问题,并导致应用程序运行缓慢。 I would suggest you to keep an index with the current image, and change it as you want (this is shown below). 我建议您保留当前图像的索引,并根据需要进行更改(如下所示)。
In my example I've calculated the minimum number of images (if separate divs have different image count). 在我的示例中,我计算了最小图像数(如果单独的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM