一、a标签跳转
- 直接a标签跳转,显得有点太生硬;加上css,实现页面平滑滚动。
<!DOCTYPE html>
<html>
<head>
<title>a-Demo</title>
</head>
<style>
.bar {
position:fixed;
top:0;
bottom:0
}
.bar a {
padding: 20px;
}
div.content div {
padding-top: 20px;
height: 1000px;
scroll-behavior: smooth;
}
html, body {
scroll-behavior:smooth;
}
</style>
<body>
<div class="bar">
<a href="#div1">跳转1</a>
<a href="#div2">跳转2</a>
<a href="#div3">跳转3</a>
</div>
<div class="content">
<div id="div1">这是div1</div>
<div id="div2">这是div2</div>
<div id="div3">这是div3</div>
</div>
</body>
</html>
<script>
</script>
二、scrollIntoView跳转
1、语法
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); //布尔参数
element.scrollIntoView(scrollIntoViewOptions); //对象参数
2、语法参数
参数名 |
参数的值 |
alignToTop |
[可选],目前之前这个参数得到了良好的支持 |
true |
元素的顶部将对齐到可滚动祖先的可见区域的顶部。对应于scrollIntoViewOptions: {block: “start”, inline: “nearest”}。这是默认值 |
false |
元素的底部将与可滚动祖先的可见区域的底部对齐。对应于scrollIntoViewOptions: {block: “end”, inline: “nearest”}。 |
参数名 |
参数的值 |
scrollIntoViewOptions |
[可选],目前这个参数浏览器对它的支持并不好,可以查看下文兼容性详情 |
behavior |
[可选]定义过渡动画。“auto”,“instant"或"smooth”。默认为"auto"。 |
block |
[可选] “start”,“center”,“end"或"nearest”。默认为"center"。 |
inline |
[可选] “start”,“center”,“end"或"nearest”。默认为"nearest"。 |
3、Demo
<!DOCTYPE html>
<html>
<head>
<title>scrollIntoView-Demo</title>
</head>
<style>
.bar {
position:fixed;
top:0;
bottom:0
}
.bar label {
padding: 20px;
}
div.content div {
padding-top: 20px;
height: 1000px;
scroll-behavior: smooth;
}
label:hover{
color: deepskyblue;
cursor:pointer;
}
</style>
<body>
<div class="bar">
<label onclick="jump('div1')">跳转1</label>
<label onclick="jump('div2')">跳转2</label>
<label onclick="jump('div3')">跳转3</label>
</div>
<div class="content">
<div id="div1">这是div1</div>
<div id="div2">这是div2</div>
<div id="div3">这是div3</div>
</div>
</body>
</html>
<script>
function jump(id) {
document.querySelector('#'+ id).scrollIntoView({behavior: "smooth"})
}
</script>