我有一个脚本可以在单击按钮时滚动窗口。工作正常,但我如何将其仅发送到目标 div?我的意思是只滚动特定的 div。
我尝试输入 getElementById
但没有成功。
scrollBy
甚至可以做到这一点吗?
<button onmousedown="skrull();" onmouseup="stop();" style="position:fixed;">Click to scroll <3</button>
<p>Some text and line breaks to enable scrolling!</p>
<script>
var skrullInterval;
function scrollWin() {
window.scrollBy(0, 100);
}
skrull = function skree() {skrullInterval = setInterval(scrollWin, 100);}
function stop() {
clearInterval(skrullInterval);
}
</script>
最佳答案
scrollBy() 和 scroll() 仅为窗口对象定义。如果你想滚动一个元素,你应该设置 scrollTop到所需的偏移量(绝对值,与 scrollBy() 不同;负值会自动转换为 0)。
element.scrollTop = 50;
来自 MDN:
The Element.scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically.
An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0.
scrollLeft 也可以水平滚动.如果您必须处理从右到左的方向,请记住这一点:
Note that if the element's direction of the element is rtl (right-to-left) then scrollLeft is 0 when the scrollbar is at its rightmost position (at start of the scrolled content) and then increasingly negative as you scroll towards the end of the content.
关于javascript - 使用 scrollBy 只滚动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144103/