码迷,mamicode.com
首页 > 其他好文 > 详细

缓速运动封装

时间:2016-12-24 19:14:49      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:animate   element   cti   script   clear   osi   function   anim   floor   

封装函数

    function animate(obj,endPosition) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var step = ( endPosition- obj.offsetLeft) /10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.style.left = obj.offsetLeft + step + ‘px‘;
            if(obj.offsetLeft == endPosition) {clearInterval(obj.timer)}
        },30)
    }

案例

<!DOCTYLE html>
<html>
<head>
    <meta charset="uft-8" />
    <style>
        #box {width:100px; height: 100px; background:#dfd; position:absolute; left:100px; top:100px;}
    </style>
</head>
<body>
<button id="btn1">200</button>
<button id="btn2">600</button>
<div id="box"></div>
</body>
</html>
<script>
    var btn1 = document.getElementById(btn1);
    var btn2 = document.getElementById(btn2);
    var box = document.getElementById(box);
    btn1.onclick = function () {
        animate(box,200)
    }
    btn2.onclick = function () {
        animate(box,600)
    }
    function animate(obj,endPosition) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
            var step = ( endPosition- obj.offsetLeft) /10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.style.left = obj.offsetLeft + step + px;
            if(obj.offsetLeft == endPosition) {clearInterval(obj.timer)}//
            //用==不要用>=,否则,在该案例中,如果已经滚动到600位置,再次点击200,将不能回到200位置
            
        },30)
    }
    
</script>

缓速运动封装

标签:animate   element   cti   script   clear   osi   function   anim   floor   

原文地址:http://www.cnblogs.com/darkterror/p/6217856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!