Element.scrollIntoView()


Element.scrollIntoView() 方法讓當前的元素滾動到瀏覽器窗口的可視區域內
語法
element.scrollIntoView();
element.scrollIntoView(alignToTop);//Boolean型參數
element.scrollIntoView(scrollIntoViewOptions);//Object型參數
參數
alignToTop (Boolean型參數)
1.如果為true,元素的頂端將和其所在滾動區的可視區域的頂端對齊。
2.如果為false,元素的底端將和其所在滾動區的可視區域的底端對齊。
scrollIntoViewOptions (Object型參數)
{
    behavior: "auto"  | "instant" | "smooth",
    block:    "start" | "end",
}
1.如果是一個boolean,true 相當於{block: "start"},false 相當於{block: "end"}
2.behavior這個選項決定頁面是如何滾動的,實測auto與instant都是瞬間跳到相應的位置,而smooth就是有動畫的過程
示例
var element = document.getElementById("box");
element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({block: "end", behavior: "smooth"});
注意
取決於其它元素的布局情況,此元素可能不會完全滾動到頂端或底端。
demo:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, minimal-ui">
<meta name="format-detection" content="telephone=no" />
<meta name="applicable-device" content="mobile">
    <title>Title</title>
    <script src="js/zepto.min.js"></script>
    <style>
        .in-top{
            width: 120px;
            height: 30px;
            line-height: 30px;
        }
        .middle{
            width: 100%;
            height: 900px;
            background-color: #95b1ff;
            border-bottom: 2px solid #f00;
        }
        #top{
            width: 100%;
            height: 800px;
            background-color: antiquewhite;
            border-bottom: 2px solid #f00;
        }
    </style>
</head>
<body>
<button class="in-top">click me</button>
<div class="middle">撐地方</div>
<div id="top">top</div>
<script>
    $(".in-top").click(function () {
        document.getElementById("top").scrollIntoView({block:"end",behavior:"smooth"});
    })
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM