js的Element.scrollIntoView的学习

1、Element.scrollIntoView()

   该方法让当前元素滚动到浏览器窗口的可是区域内;

2、语法:
element.scrollIntoView();//等同于element.scrolIntoView(true)
element.scrollIntoView(alignToTop);//Boolean型参数
element.scrollIntoView(scrollIntoViewOptions);//Object型参数

参数
alignToTop:true--- 元素的顶端和器所在滚动区的可视区域顶端对齐
true 相当于{block:start}
false--- 元素的底端将和其所在滚动区的可视区域底端对齐
false 相当于{block:end}
scrollIntoViewOptions:一个boolean值或一个带有选项的object
{
behavior:'auto' | 'instant'|'smooth',
block:'start' | 'end'
}
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>scrollToView的学习</title>
 6     <style>
 7         #containers{
 8             background-color: black;
 9             300px;
10             height:50px;
11             display: flex;
12             justify-content: space-around;
13             position: fixed;
14             left:42.1%;
15         }
16         .clear{
17             height:50px;
18         }
19         .title{
20             color: #ffffff;
21         }
22         #title1-item,#title2-item,#title3-item{
23             300px;
24             height:800px;
25             border:1px solid #dddddd;
26             margin: auto;
27             margin-bottom: 20px;
28             box-sizing: border-box;
29             padding-top: 50px;
30         }
31     </style>
32 </head>
33 <body>
34  <div id="containers">
35      <div data-target="#title1-item" class="title">商品</div>
36      <div data-target="#title2-item" class="title">详情</div>
37      <div data-target="#title3-item" class="title">评价</div>
38  </div>
39  <div class="clear"></div>
40  <div id="title1-item">商品对应的部分</div>
41  <div id="title2-item">详情对应的部分</div>
42  <div id="title3-item">评价对应的部分</div>
43  <script type="text/javascript">
44      var aHref = document.getElementsByClassName('title');
45      var title1Item = document.getElementById('title1-item');
46      var title2Item = document.getElementById('title2-item');
47      var title3Item = document.getElementById('title3-item');
48      console.log(aHref[0]);
49      aHref[0].onclick=function(){
50          title1Item.scrollIntoView(true);
51 
52      };
53      aHref[1].onclick=function(){
54          title2Item.scrollIntoView(false);
55 
56      };
57      aHref[2].onclick=function(){
58          title3Item.scrollIntoView();
59      }
60  </script>
61 </body>
62 </html>
3、浏览器支持
scrollIntoViewOptions IE浏览器,Safari 不支持
IE8版本以下,Safari 5.0版本以下 不支持 "smooth" 属性 和 "center" 设置项.
Firefox 36 不支持 "inline" 设置项。不支持设置项的值 "nearest" 或 "center"。
移动端:
scrollIntoViewOptions 会有一些低配版本的手机不支持

原文地址:https://www.cnblogs.com/bllx/p/8477989.html