Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型参数 true 元素的顶端与可视区域顶端对齐,(相当于{block: "start"}) false 元素底端将与可视区域底端对齐(相当于{block: "end"})
element.scrollIntoView(scrollIntoViewOptions); // Object型参数 behavior: "auto" | "instant" | "smooth",behavior这个选项决定页面是如何滚动的,auto与instant都是瞬间跳到相应的位置,而smooth就是有动画的过程;block:"start" | "end"
===================================================================
element.scrollIntoView() 方法不但可以引起页面的垂直滚动,也可以引起页面的水平滚动,这个是合理的
实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div { height: 1500px; width: 150%; background: #ddd; margin: 20px auto; border: 1px solid #aaa; }
p { position: relative; }
#link { position: absolute; right: -200px; }
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<p><a id="link">aaaa</a>占位符占位符占位符</p>
<div id="div3"></div>
<script>
function aaa() {
var element = document.getElementById("link");
element.scrollIntoView({ block: "end", behavior: "smooth" });
}
setTimeout(function () {
aaa();
}, 2000)
</script>
</body>
</html>
效果如下
另外,element.scrollIntoView()还会引起一些看似诡异但情理上说的过去的现象,比如 element是不可见的,将element放到overflow:hiden的容器或者将element设置为visibility: hidden;会改变原有布局
例如
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div { height: 1500px; width: 150%; background: #ddd; margin: 20px auto; border: 1px solid #aaa; }
p { white-space: nowrap; width: 200px; text-overflow: ellipsis; overflow: hidden; }
#link { visibility: hidden; }
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<p>
占位符占位符占位符占位符<a id="link">aaaa</a>占位符占位符占位符
</p>
<div id="div3"></div>
<script>
function aaa() {
var element = document.getElementById("link");
element.scrollIntoView({ block: "end", behavior: "smooth" });
}
setTimeout(function () {
aaa();
}, 2000)
</script>
</body>
</html>
初始状态 #link在这个位置
scrollIntoView之后
当我们改变容器的宽度再改回来,样式又恢复了
参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
https://www.jianshu.com/p/32bef36a68a0