小米滚动

编辑本博客

  • this.onmouseover()鼠标悬浮在对象上
  • this.onmouseout()鼠标从对象上移除,还有其他很多方法
  • 善用定时器清理
  • 留意index值,可能在对象上存在其他对象,导致鼠标移动上去方法不生效
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小米滚动</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        .wrap{
            width: 298px;
            height: 198px;
            top: 10px;
            position: relative;
            margin: 0 auto;
            background-color: transparent;
            overflow: hidden;
            border: 1px solid blue;
            /*background-image: url("img/long.jpg");*/
            /*-webkit-background-size: 300px;*/
            /*background-size: 300px;*/
        }
        .up,.down{
            display: block;
            width: 300px;
            height: 100px;
            position: relative;
            /*border:1px solid red;*/
        }
        img{
            position: absolute;
            width: 300px;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div id="box" class="wrap">
    <img src="img/long.jpg" id="long">
    <span class="up" id="picUp">A</span>
    <span class="down" id="picDown">B</span>
</div>
</body>
<script type="text/javascript">
    var up=document.getElementById('picUp');
    var down=document.getElementById('picDown');
    var img=document.getElementById("long");
    var timer=null;
    var content=0//当前top位置
    up.onmouseover=function (ev) {
        clearInterval(timer);//清除定时器
        timer=setInterval(function () {
            content-=1;
            if(-885<=content){
                img.style.top=content+"px";
            }else {
                clearInterval(timer);
            }
        },10)

    }
    down.onmouseover=function (ev) {
        clearInterval(timer);
        timer=setInterval(function () {
            content+=1;
            if(content<0){
                img.style.top=content+"px";
            }else {
                clearInterval(timer);
            }
        },10)

    }
    //鼠标移除则清除定时器
    up.onmouseout=function (ev) {
        clearInterval(timer);
    };
    down.onmouseout=function (ev) {
        clearInterval(timer);
    };

</script>
</html>
View Code
原文地址:https://www.cnblogs.com/yaya625202/p/9192237.html