当连续单击不同的选项卡时,如何防止文本截断?

How can I prevent the text from truncating when different tabs are clicked in succession?

本文关键字:何防止 文本 单击 连续 选项      更新时间:2023-09-26

所以我有一个type writer效果,它响应选项卡的点击。一旦单击选项卡,内容框就会改变,并开始输入效果,相应的选项卡也会改变。但是,如果我点击一个选项卡,比如单击选项卡1,然后单击选项卡2,然后快速连续或甚至中等连续地返回到选项卡1,内容框的文本就会突然结束,字体效果也不会打印出所有的文本。

$(document).ready(function () {
    $('div#tab-wrapper div.myTabs').click(function () {
        var tab_id = $(this).attr('data-tab');
        $('div.content').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
        typeWriterEffect(tab_id, document.getElementById(tab_id).innerHTML, 50);
    });
});
var timer;
function typeWriterEffect(id, sentence, speed) {
    var index = 0; //reset index
    clearInterval(timer); //clear old timer
    document.getElementById(id).innerHTML = ""; //clear it immediately to prevent flicker on click
    timer = setInterval(function () {
        var char = sentence.charAt(index);
        if (char === '<') index = sentence.indexOf('>', index);
        document.getElementById(id).innerHTML = sentence.substr(0, index);
        index++;
        if (index === sentence.length) {
            clearInterval(timer);
        }
    }, speed);
}

我想我可以将innerHTML文本存储到data()方法中,但这似乎不起作用,或者我做错了,同样的结果。

无论如何,这是我刚才讲的所有内容的JSFiddle。

这可能是因为每次调用typeWriterEffect()时都清除了全局计时器。尝试将其用作局部变量,在函数内部声明。

$(document).ready(function () {
    $('div#tab-wrapper div.myTabs').click(function () {
        var tab_id = $(this).attr('data-tab');
        $('div.content').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
        typeWriterEffect(tab_id, document.getElementById(tab_id).innerHTML, 50);
    });
});
var timer;
function typeWriterEffect(id, sentence, speed) {
    var self = this;
    var index = 0; //reset index
    self.timer = setInterval(function () {
        var char = sentence.charAt(index);
        if (char === '<') index = sentence.indexOf('>', index);
        document.getElementById(id).innerHTML = sentence.substr(0, index);
        index++;
        if (index === sentence.length) {
            clearInterval(self.timer);
        }
    }, speed);
    clearInterval(self.timer); //clear old timer
    document.getElementById(id).innerHTML = ""; //clear it immediately to prevent flicker on click
}
http://jsfiddle.net/7V4NA/34/