javascript - 使用 scrollBy 只滚动 div

标签 javascript html css scroll

我有一个脚本可以在单击按钮时滚动窗口。工作正常,但我如何将其仅发送到目标 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/

相关文章:

javascript - 带有 ES6 的 Angular 1.5.0 - Controller 导出不工作

Javascript 从数组中检索购物车的值?

CSS 布局页脚 DIV 以 100% 高度消失

css - 悬停在另一个 DIV 上时显示 DIV

css - 如何在两个高度动态变化的 div 之间创建边框?

javascript - 在粘贴事件中获取文档中粘贴的内容

javascript - 当我们只有 child 的id时,如何使用js更改父div的宽度和高度

javascript - html/javascript 中的 android spinner

html - 包含行内 block 元素的 block 元素的高度

php - 在脚本末尾在网站上绘制图像