JS实现页面滚动

作者: sky丶星如雨 | 来源:发表于2017-06-28 11:47 被阅读39次
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .mi{
            width: 512px;
            height: 400px;
            margin:100px auto;
            overflow: hidden;
            position: relative;
        }
        .mi span{
            position: absolute;
            left:0;
            width:100%;
            height: 50%;
            cursor: pointer;
        }
        #picUp{
            top:0;
        }
       #picDown{
            bottom:0
        }
        #pic{
            position: absolute;
            top:0;
            left:0;
        }
    </style>
</head>
<body>
<div class="mi">
   <img src = "images/mi.png">
    <span id="picUp"></span>
    <span id="picDown"></span>
</div>
<script>
        function $(id) {
            return document.getElementById(id);
        }
        var timer = null; // 定义定时器
        var count = 0;  // 定义top值
        
        //  鼠标悬浮上半部分时,图片向上滚动
        $("picUp").onmouseover = function () {
            clearInterval(timer);  // 清除定时器
            timer = setInterval(function () {  // 开启定时器
                count -= 3;
                if(count >= -1070){ 
                    $("pic").style.top = count + "px";
                }else{
                        clearInterval(timer);
                }
            },30)
        }

        //  鼠标悬浮下半部分时,图片向下滚动
        $("picDown").onmouseover = function () {
            clearInterval(timer);
            timer = setInterval(function () {
                count ++;
                if(count <= 0){
                    $("pic").style.top = count + "px";
                }else{
                    clearInterval(timer);
                }
            },20)
        }

        // 当鼠标移出时,停止定时器

        $("picUp").parentNode.onmouseout = function () {
            clearInterval(timer);
        }

</script>
</body>
</html>

相关文章

网友评论

    本文标题:JS实现页面滚动

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