当Web页面的内容高度或宽度超过可视区域时,页面才能滚动。Web页面滚动有多种方式,包括使用外接设备、ArkTS侧接口调用和JS侧接口调用。
可以使用以下方式,通过触屏、触摸板和鼠标滚轮控制Web页面滚动。
scrollTo:在指定时间内,将页面滚动到指定的绝对位置。
返回页面顶部。
this.webController.scrollTo(0, 0);
scrollBy:在指定时间内将页面滚动指定的偏移量。
可以作为Web组件嵌套滚动中,控制Web组件滚动的接口,详见滚动偏移量由滚动父组件统一派发。
pageUp:将Web组件的内容向上滚动半个视口大小或者滚动到页面最顶部,通过top入参控制。
pageDown:将Web组件的内容向下滚动半个视口大小或者滚动到页面最底部,通过bottom入参控制。
scrollBy:相对当前滚动位置滚动一定距离(正数向下/右,负数向上/左)。
window.scrollBy(deltaX, deltaY);// deltaX是元素要在横轴上滚动的距离,deltaY是元素要在纵轴上滚动的距离。
渐进式滚动(如“阅读更多”按钮)。
document.getElementById("read-more").addEventListener("click", ()=>{
window.scrollBy(0, 300);
}) scrollTo:将页面滚动到绝对坐标位置。
window.scrollTo(x, y);// x是滚动后窗口左上角的水平坐标(像素),y是滚动后窗口左上角的垂直坐标(像素)。
(1) 返回页面顶部。
window.scrollTo(0, 0);
(2) 跳转到页面特定位置。
window.scrollTo(0, 500); // 滚动到某个固定像素位置(如:500px)
当Web页面处于非顶部状态或向下抛滑时,此时若需返回Web页面顶部,可以使用backToTop方法,开启后通过点击状态栏,打断抛滑并将Web页面滚动到页面顶部。
示例代码:
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile("index.html"), controller: this.controller })
.backToTop(true)
}
}
} 加载的HTML文件:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
<style>
.blue {
background-color: lightblue;
}
.green {
background-color: lightgreen;
}
.blue, .green {
font-size:16px;
height:200px;
text-align: center; /* 水平居中 */
line-height: 200px; /* 垂直居中(值等于容器高度) */
}
</style>
</head>
<body>
<div class="blue" >webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
</body>
</html> 效果展示:
