利用原生方法我们可以做类似目录导航一类的锚点功能
Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。
案例
var box = document.getElementById("box");
box.scrollIntoView();
box.scrollIntoView(false);
如果使用vue或者react,推荐用ref做动态标记用来捕获元素
scrollIntoView默认可视区顶部
alignToTop可选
一个Boolean值:
如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。
相应的 scrollIntoViewOptions: {block: "start", inline: "nearest"}。
这是这个参数的默认值。
如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐。
相应的scrollIntoViewOptions: {block: "end", inline: "nearest"}
默认使用true和false
scrollIntoView可配参数scrollIntoViewOptions
scrollIntoViewOptions 可选
一个包含下列属性的对象:
behavior 可选
定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"。
block 可选
定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"。
inline 可选
定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"。
案例
import React, { Component } from 'react';
import './style.less';
class Home extends Component {
constructor(props, context) {
super(props, context);
this.state = {
list: [1, 2, 3, 4, 5, 6, 7, 9, 10, 11]
}
}
jump = (ref) => {
this.refs[ref].scrollIntoView({
behavior: "smooth",
block: "end",
inline: "nearest"
})
}
render() {
const { list } = this.state
return (
<div className="home">
<div className="fix">
<ul>
{
list.map((e, i) => <li key={i} onClick={() => this.jump(e)}>{e}</li>)
}
</ul>
</div>
{
list.map((e, i) => <div className="box" key={i} ref={e}>第{e}个</div>)
}
</div>
);
}
}
export default Home;
样式文件
.home{
text-align: center;
.fix{
position: fixed;
li {
color: #fff;
width: 200px;
font-size: 20px;
line-height: 40px;
background-color: #333;
margin-bottom: 10px;
cursor: pointer;
}
}
.box {
height: 400px;
font-size: 40px;
font-weight: 700;
border: 1px solid rgb(235, 232, 232);
margin-bottom: 20px;
}
}
效果如下:点击导航6,页面滚动到6的位置,为可视区底部与6底部对齐