美文网首页前端札记让前端飞Web前端之路
返回顶部效果---原生JavaScript手作

返回顶部效果---原生JavaScript手作

作者: kerush | 来源:发表于2017-04-15 13:42 被阅读84次
    前端入坑纪 08

    每逢周六必更新啊!自从写简书开始,发现这一周周时间过得可真快。白天忙着写业务代码,晚上回去为发文查资料。偶尔偷闲看看电视,时间一晃就周末了......

    截图.png

    一等大事:项目链接

    HTML 结构
        <a id="top" href="javascript:;">Top</a>
        <div class="wrp">
            <ol>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
                以下省略很多个li
            </ol>
        </div>
    
    CSS结构
            body {
                margin: 0;
                padding: 0
            }
            
            a {
                text-decoration: none;
            }
            
            ol {
                margin: 0;
            }
            
            body {
                background-color: #fefefe;
            }
            
            #top {
                opacity: 0;
                display: none;
                position: fixed;
                right: 12px;
                bottom: 12px;
                width: 45px;
                height: 45px;
                line-height: 45px;
                color: #fff;
                border-radius: 50%;
                text-align: center;
                font-weight: bold;
                transition: all 1s ease;
                background-color: rgba(0, 0, 0, .5)
            }
    

    css的关键是设置top,全透明,有过渡

    JavaScript结构
            var oTop = document.getElementById('top'),
                owhet = window.innerHeight,
                obody = document.body;
    
            // 当网页被卷过超过整个屏幕的高度时,切换top按钮的透明为1,不然就是0
            function toggleOpacity() {
                var stp = obody.scrollTop;
                console.log(stp);
                if (stp > owhet) {
                    oTop.style.display = "block";
                    setTimeout(function() {
                        oTop.style.opacity = 1;
                    }, 10);
                } else {
                    oTop.style.display = "none";
                    oTop.style.opacity = 0;
                }
            }
    
            // 当点击top按钮时,每30毫秒减少当前stp的一半,直至为0时,清除计时器
            function toTheTop() {
                var timer = setInterval(function() {
                    var stp = obody.scrollTop;
                    if (stp > 0) {
                        stp -= stp / 2;
                        obody.scrollTop = stp;
                    } else {
                        clearInterval(timer)
                    }
                }, 30)
            }
    
            oTop.onclick = toTheTop;
            obody.ontouchmove = obody.onscroll = toggleOpacity;
    

    这个效果还是挺有用的,移动端和PC端都有类似的效果

    相关文章

      网友评论

      • 2241c572b526:這樣子,一開始就會存在吧? 這樣子透明度還沒顯示出來就能觸發toTheTop了吧?
        kerush:好了,现在已经改成display:none了
        kerush: @肝醣 透明的看不到,想点还是会点到,可以改成diaplay:none

      本文标题:返回顶部效果---原生JavaScript手作

      本文链接:https://www.haomeiwen.com/subject/kyjnattx.html