使用setInterval / clearInterval自动滚动 [英] Autoscroll with setInterval/clearInterval
问题描述
我对JS编码相对较新,并且不能让这个小数字起作用。谁能告诉我我做错了什么?
Im relatively new to JS coding, and can't get this little number to work. Can anyone tell me what I'm doing wrong?
我的JavaScript是:
My JavaScript is:
incrementScroll = function() {
window.scrollBy(0, 3) ;
}
startScrollLoop = function() {
scrollLoopId = setInterval( "incrementScroll", 5) ;
}
stopScrollLoop = function() {
clearInterval( scrollLoopId ) ;
}
我的HTML是:
<button onclick="startScrollLoop()">AUTO SCROLL</button>
<button onclick="stopScrollLoop ()">STOP SCROLL</button>
再次,非常感谢您的帮助。所有这一切都是新手,需要在早上之前完成一个项目。
干杯。
Again, many thanks for help. New to all of this and need to make a project work by morning. Cheers.
推荐答案
的第一个参数setInterval()
应该是一个函数引用,或者非理想情况下,一个字符串是eval()'d,这将是一个完整的函数调用()
。所以删除引号:
The first argument to setInterval()
should be a function reference, or non-ideally, a string to be eval()'d, which would be a complete function call with ()
. So remove the quotes:
// Pass the reference to incrementScroll,
// not a quoted string containing its name.
scrollLoopId = setInterval(incrementScroll, 5);
要清除滚动,您需要定义 scrollLoopId
在更高的范围内, var
。
And to clear the scroll, you will need to define scrollLoopId
at a higher scope with var
.
// Define outside the function so it is available
// in scope of the stopScrollLoop() function when needed...
var scrollLoopId;
var startScrollLoop = function() {
scrollLoopId = setInterval( incrementScroll, 5) ;
}
Jsfiddle演示
(使用较慢的滚动速度让您有机会点击中间的停止按钮文本)
Jsfiddle demo
(uses a slower scroll speed to give you a chance to click the stop button in the middle of the text)
请注意,最好对每个使用 var
关键字。即使他们最终会在窗口
范围内结束(假设他们没有在另一个函数中定义)。
Note that it is good practice to use the var
keyword with each of these. even though they would end up at window
scope anyway (assuming they're not being defined inside another function).
// Define with var
var incrementScroll = function() {
window.scrollBy(0, 3);
}
这篇关于使用setInterval / clearInterval自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!