js回到顶部

今晚,我自己写了一个很简单的回到的顶部的js,同时也希望自己能在原生JS上面有发展,与大家共勉!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript backToTop</title>
</head>
<body>
    <div style="width:100%;height:1000px;"></div>   
    <script type="text/javascript">
        ;(function(){
            var container = document.createElement('div'),
                body = document.getElementsByTagName('body')[0],
                doc = document.body,
                style = [
                    "border: 1px solid #ccc;",
                    "position: fixed;",
                    "width: 40px;",
                    "height: 40px;",
                    "bottom: 100px;",
                    "left: 50%;",
                    "margin-left: 500px;",
                    "z-index: 9999;",
                    "cursor: pointer;",
                    "display: none;"
                ].join(""),
                icon = document.createElement('div'),
                iconStyle = [
                    "width: 10px;",
                    "height: 10px;",
                    "position: absolute;",
                    "border-top: 2px solid #ccc;",
                    "border-left: 2px solid #ccc;",
                    "top: 18px;",
                    "left: 15px;",
                    "transform: rotate(45deg);",
                    "-webkit-transform: rotate(45deg);",
                    "-moz-transform: rotate(45deg);",
                    "-o-transform: rotate(45deg);"
                ].join("");
                container.style.cssText = style;
                icon.style.cssText = iconStyle;
                container.appendChild(icon);
                body.appendChild(container);
                window.addEventListener('scroll',function(){
                    var scrollTop = doc.scrollTop;
                    console.log(scrollTop);
                    if(scrollTop > 200) {
                        container.style.display = "block";
                    } else {
                        container.style.display = "none";
                    }
                },false);
                container.addEventListener('click',function(){
                    setTimeout(function() {
                        document.body.scrollTop = 0;
                    },0);
                },false);
        })();
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值