欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Js控制鼠标滑动图片

程序员文章站 2024-03-04 13:40:23
...
<div class="all" id="all">
    <img src="./images/mi.png" id="mi">
    <div id="up"></div>
    <div id="down"></div>
</div>
<style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        .all{
            width: 512px;
            height: 400px;
            margin: 100px auto;
            overflow: hidden;
            position: relative;
        }

        #up{
            width: 512px;
            height: 200px;
            position: absolute;top:0px;
        }

        #down{
            width: 512px;
            height: 200px;
            position: absolute;bottom: 0px;

        }

        #mi{
            position: absolute;
        }

    </style>
<script type="text/javascript">
    window.onload = function(){
        function $(id) {
            return document.getElementById(id);
        }

        var num = 0;
        var timer = null;
        // //控制图片向上移动
        $("up").onmouseover = function (){
            timer = setInterval(fun,30);

                function fun(){
                    num-=2;
                if(num<-1070){
                    clearInterval(timer);
                }else{
                    $("mi").style.top=num+"px";
                }
            }
        }
         //控制图片向下移动
        $("down").onmouseover = function (){
            timer = setInterval(fun,30);
                function fun(){
                    num+=2;
                if(num>0){
                    clearInterval(timer);
                }else{
                    $("mi").style.top=num+"px";
                }
                }

        }

        //鼠标移走后图片停止移动
        $("all").onmouseout = function(){
            clearInterval(timer);
        }
    }
    </script>

Js控制鼠标滑动图片