滚动相关
Element.scroll()
scroll() 方法是用于在给定的元素中滚动到某个特定坐标的 Element 接口。当前元素为可滚动的元素即外层元素
scroll(x-coord, y-coord)
scroll(options)
//参数
x-coord 到达位置水平轴像素值
y-coord 到达位置垂直轴像素值
options:{
top:y轴像素值,
left:x轴像素值,
behavior: 过度效果 (smooth, auto)
}
Element.scrollBy()
scrollBy() 方法是使得元素滚动一段特定距离的 Element 接口。当前元素为可滚动元素。参数同 scroll()
;
Element.scrollIntoView()
Element接口的 scrollIntoView() 方法会滚动元素的父容器,使被调用 scrollIntoView() 的元素对用户可见。当前元素为可滚动元素的子元素。
element.scrollIntoView({ block: "end" });
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
//参数
behavior
定义滚动是立即的还是平滑的动画。
smooth:滚动应该是平滑的动画。
instant:滚动应该通过一次跳跃立刻发生。
auto:滚动行为由 scroll-behavior 的计算值决定。
block
定义垂直方向的对齐,start、center、end 或 nearest 之一。默认为 start。
inline
定义水平方向的对齐,start、center、end 或 nearest 之一。默认为 nearest。
- 实例-在react中使用
const scrollToBox=()=>{
const element = document.getElementById('content');
if (element) {
element.scroll(0,500)
//element.scrollBy(0,500)
//element.scrollIntoView({ behavior: 'smooth' });
}
}
return <div>
<div style={{height:'80vh',width:'80%',overflow:'scroll'}} id='content'>
<button onClick={scrollToBox}>滑动</button>
<div style={{height:'500px'}}></div>
<div style={{height:'200px',background:'blue',margin:'20px'}} id="content-title"></div>
<div style={{height:'1000px'}}></div>
</div>
</div>
锚点
<a>
a元素(或称锚元素)可以通过它的 href 属性创建通向其他网页、文件、电子邮件地址、同一页面内的位置或任何其他 URL 的超链接。
<!-- <a> 元素链接到下面部分 -->
<p><a href="#Section_further_down"> 跳转到下方标题 </a></p>
<!-- 要链接到的标题 -->
<h2 id="Section_further_down">更下面的部分</h2>