如何为每个班级应用一个功能的效果?

时间:2017-03-12 17:19:47

标签: javascript jquery html

我将此代码随机随机播放并创建悬停效果。我用它来导航。 但似乎我的代码仅适用于单个类,当我放置多个类时,它会破坏所有内容并同时为所有内容生成一个shuffle,无限期......

当心:请谨慎使用该片段,否则会导致导航器崩溃......



// Shuffle
jQuery(function($) {
    function text_shuffle() {
        "use strict";
        var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*?><[]&@#)(.%$-_:/;?!";
         $_inter = setInterval(function() {
            var text = $(".text-shuffle").text();
            text = text.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.substring(counter+1);
            $(".text-shuffle").text(text);
            counter = (counter+1)%text.length;
        }, 150);
    }
    var value, $_inter;

    $(".text-shuffle").mouseenter( function(){
        value  = $(this).html();
        text_shuffle();
    }).
    mouseout(function(){
        clearInterval($_inter);
        $(this).html(value);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="text-shuffle">Title 1</div>

<div class="text-shuffle">Title 2</div>

<div class="text-shuffle">Title 3</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

如果将当前元素传递给函数,则可以限制范围如下:

// Shuffle
jQuery(function($) {
    function text_shuffle($element) {
        "use strict";
        var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*?><[]&@#)(.%$-_:/;?!";
         $_inter = setInterval(function() {
            var text = $element.text();
            text = text.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.substring(counter+1);
            $element.text(text);
            counter = (counter+1)%text.length;
        }, 150);
    }
    var value, $_inter;

    $(".text-shuffle").mouseenter( function(){
        value  = $(this).html();
        text_shuffle($(this));
    }).
    mouseout(function(){
        clearInterval($_inter);
        $(this).html(value);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="text-shuffle">Title 1</div>

<div class="text-shuffle">Title 2</div>

<div class="text-shuffle">Title 3</div>