这个问题主要关注我在尝试执行代码时遇到的这个问题。
我的代码到目前为止......
var position = $("#second").offset();
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y >= position.top) {
//text that belongs on second slide
var text = "Lorem ipsum dolor sit amet... consectetur adipiscing elit. Praesent sagittis sodales ex vel pellentesque. Vestibulum quis arcu odio. Curabitur feugiat lorem quis luctus faucibus. ";
//text is split up to letters
$.each(text.split(""), function (i, letter) {
//we add 100*i ms delay to each letter
setTimeout(function () {
//we add the letter to the container
$("#text").html($("#text").html() + letter);
}, 80 * i);
});
}
});
一旦你点击一个按钮滚动到下一张幻灯片,这个想法就是让文本开始做“打字机”动画。它工作正常,但只有当我按下按钮。如果我用鼠标向下滚动代码会发疯。请参见此处:preview from where i host my code / jsfiddle
你可以向下滚动,文本不会在JSfiddle中疯狂,但不会在我托管我的代码的网站上。但是,如果你向上滚动并在JSfiddle上向下滚动,文本就会变得疯狂。
另外,是的,我知道闪烁的文字是不受欢迎的,请不要对此发表评论。
答案 0 :(得分:1)
这种情况正在发生,因为每次向上和向下滚动(在小提琴中),该功能都会一次又一次地触发。一个简单的解决方案是使用变量作为检查。设置一些变量tok false
,滚动时如果该变量等于false
,则运行脚本并将其设置为true
(因此它不会再次触发)< / p>
var triggered = false;
...
if(y >= position.top && triggered === false){
triggered = true; //the above line will return false and won't fire the function