Window scrollBy() 方法
实例
将文档水平滚动 100px:
<!DOCTYPE html>
<html>
<head>
<style>
body {
width: 5000px;
}
button {
position: fixed;
}
</style>
</head>
<body>
<p>单击该按钮可将文档窗口水平滚动 100px。</p>
<p>查看水平滚动条以查看效果。</p>
<button onclick="scrollWin()">单击水平滚动!</button><br><br>
<script>
function scrollWin() {
window.scrollBy(100, 0);
}
</script>
</body>
</html>
定义与用法
scrollBy()
方法按指定的像素数滚动文档。
注意:要使此方法可用,必须将窗口滚动条的 visible
属性设置为 true!
浏览器支持
方法 | |||||
---|---|---|---|---|---|
scrollBy() | Yes | Yes | Yes | Yes | Yes |
语法
window.scrollBy(xnum, ynum)
参数值
参数 | Type | 描述 |
---|---|---|
xnum | Number | 必填。沿 x 轴(水平)滚动的像素数。正值将向右滚动,负值将向左滚动 |
ynum | Number | 必填。沿 y 轴(垂直方向)滚动的像素数。正值向下滚动,负值向上滚动 |
技术细节
返回值: | 无返回值 |
---|
更多实例
实例
将文档垂直滚动 100px:
<!DOCTYPE html>
<html>
<body>
<p>单击该按钮可将文档窗口垂直滚动 100px。</p>
<button onclick="scrollWin()" style="position:fixed;">单击垂直滚动!</button>
<br><br>
<p>一些文本和换行符以确保能够滚动!</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p>
<br>
<br>
<script>
function scrollWin() {
window.scrollBy(0, 100);
}
</script>
</body>
</html>
实例
水平和垂直滚动文档:
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 7500px;
width: 5000px;
}
button {
position: fixed;
}
</style>
</head>
<body>
<p>单击其中一个按钮(多次)滚动文档窗口。</p>
<p>查看每个滚动条以查看效果。</p>
<button onclick="scrollWin(0, 50)">向下滚动</button><br><br>
<button onclick="scrollWin(0, -50)">向上滚动</button><br><br>
<button onclick="scrollWin(100, 0)">向右滚动</button><br><br>
<button onclick="scrollWin(-100, 0)">向左滚动</button><br><br>
<script>
function scrollWin(x, y) {
window.scrollBy(x, y);
}
</script>
</body>
</html>
相关页面
Window 对象: scrollTo() 方法