现在的位置: 首页 > 综合 > 正文

一个JavaScript的分享到效果

2013年06月08日 ⁄ 综合 ⁄ 共 1144字 ⁄ 字号 评论关闭

这个效果是体现了元素运动的基本原理。

 

View Code

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      .share { position: absolute;top:50px;left:-100px;width:100px;height:300px;background-color: gray;}
      .share span { position: absolute;right: -24px;top:130px;padding:5px 2px;width:20px;background-color:#dadada;font-size: 12px;color: #fff;text-align: center;cursor: pointer;}
    </style>
    <script type="text/javascript">
        window.onload = function(){
            var share = document.getElementById('s');
            var span = share.getElementsByTagName('span')[0];
            var speed = 0;        
            var timer = null;

            share.onmouseover = function(){
                startMove(0);
            }
            share.onmouseout = function(){
                startMove(-100);
            }            
        
            function startMove(terminal){        

                
                clearInterval(timer);
                timer = setInterval(function(){    

                    if(share.offsetLeft < terminal){
                        speed = 10;
                    }else{
                        speed = -10;
                    }
     
                    if(share.offsetLeft == terminal){                 
                        clearInterval(timer);                                        
                    }else{
                        share.style.left = share.offsetLeft + speed + 'px';
                        //console.log(share.offsetLeft)
                    }

                },30);

            }
        }
    </script>
</head>
<body>
    <div class="share" id="s">
        <span>分享到</span>
    </div>
</body>
</html>

 

写的时候,遇到3个问题,尽管是看视频学的。

 

1、运动的停止条件。

2、触发的元素。

有必要说这个东西,我之前把span当作了触发的对象,结果就有许多的bug。熟悉冒泡的话,你就知道事件总是从最底层元素开始的。所以……我没话说,基础知识都想半天,还好解决了,不然真的没有面目了。

3、速度正负判断。

抱歉!评论已关闭.