js 原生拖拽

來源:互聯網
上載者:User

標籤:nav   utf-8   charset   char   pos   int   als   sed   type   

拖拽效果很是普遍 今天拿原生簡單寫一下

(可以按拖拽軌跡 返回到原點)

 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
        color:#666;
    }
    div{
        height: 150px;
        width: 300px;
        border: 1px solid #ccc;
        position: absolute;
        left: 150px;
        top: 150px;
    }
    h5{
        line-height: 35px;
        text-align: right;
        padding-right: 12px;
        border-bottom: 1px solid #ccc;
        cursor: move;
    }
    h5 span{
        cursor: pointer;
    }
    li{
        list-style: none;
        line-height: 25px;
        padding-left: 12px;
    }
</style>
<body>
    <div id="box">
        <h5 id="nav"><span id="back">點擊我原路返回</span></h5>
        <ul>
            <li>Drag: <span>false</span></li>
            <li>Top:  <span>150</span></li>
            <li>Left: <span>150</span></li>
        </ul>
    </div>
</body>
</html>

<script type="text/javascript">
    
var box=document.getElementById("box"),
    nav=document.getElementById("nav"),
    back=document.getElementById("back"),
    spans=document.getElementsByTagName("span"),
    rouse=[{x:box.offsetLeft,y:box.offsetTop}],
    Drag=false;
    
    nav.onmousedown=function(){
        
        Drag=true;
    }

    document.onmousemove=function(e){
        var e=e || window.e;
        if(!Drag) return false;

        box.style.left=e.clientX-30+"px";
        box.style.top=e.clientY-17+"px";
        rouse.push({x:box.offsetLeft, y:box.offsetTop});
        offset();
    }

    document.onmouseup=function(){
        Drag=false;
        offset();
    }
    back.onclick=function(){
        console.log(rouse);
        if(rouse.length==1) return false;
        var timer=setInterval(function(){
            var oPos =rouse.pop();
            oPos ? (box.style.left =oPos.x + "px", box.style.top = oPos.y + "px", offset()) : clearInterval(timer)
            console.log(oPos);
        },30)
    }

    function offset(){
        spans[1].innerHTML=Drag;
        spans[2].innerHTML=box.offsetLeft;
        spans[3].innerHTML=box.offsetTop;
    }
    box.ontouch

</script>

還望各位多多指點!!!

js 原生拖拽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.