scrollToAnchor 和 scrollintoviewifneeded


1.scrollToAnchor:MND定义此方法让当前的元素滚动到浏览器窗口的可视区域内。

语法:

element.scrollIntoView(); // 等同于element.scrollIntoView(true) 
element.scrollIntoView(alignToTop); // Boolean型参数 
element.scrollIntoView(scrollIntoViewOptions); // Object型参数

参数:

alignToTop一个 Boolean值:
  • 如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。
  • 如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐。
scrollIntoViewOptions一个boolean或一个带有选项的object:
{
    behavior: "auto"  | "instant" | "smooth",
    block:    "start" | "end",
}
如果是一个boolean,  true  相当于 {block: "start"} false  相当于 {block: "end"}

示例:

var element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({block: "end", behavior: "smooth"});
实际使用中,可封装成一个方法,代码如下,再需要根据锚点跳转的地方是调用这个方法,然后再html中去写对应的id;
// 锚点 
scrollToAnchor = (anchorName) => {
    if (anchorName) {
        // 找到锚点
        let anchorElement = document.getElementById(anchorName);
        // 如果对应id的锚点存在,就跳转到锚点
        if (anchorElement) { 
            anchorElement.scrollIntoView(); 
        }
    }
}

2. scrollIntoViewIfNeeded :MND的定义此方法用来将不在浏览器窗口的可见区域内的元素滚动到浏览器窗口的可见区域。 如果该元素已经在浏览器窗口的可见区域内,则不会发生滚动。 此方法是标准的Element.scrollIntoView()方法的专有变体。

语法:

element.scrollIntoViewIfNeeded(); // 等同于element.scrollIntoViewIfNeeded(true) 
element.scrollIntoViewIfNeeded(true); 
element.scrollIntoViewIfNeeded(false);

参数:

opt_center一个  Boolean 类型的值,默认为 true:
  • 如果为true,则元素将在其所在滚动区的可视区域中居中对齐。
  • 如果为false,则元素将与其所在滚动区的可视区域最近的边缘对齐。 根据可见区域最靠近元素的哪个边缘,元素的顶部将与可见区域的顶部边缘对准,或者元素的底部边缘将与可见区域的底部边缘对准。

示例:

var element = document.getElementById("child"); 

element.scrollIntoViewIfNeeded();
element.scrollIntoViewIfNeeded(true);
element.scrollIntoViewIfNeeded(false);



你可能感兴趣的:(WEB)