Element.scrollIntoView()

本文详细介绍了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>

转载于:https://www.cnblogs.com/xiaoleidiv/p/9895006.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值