首頁  >  文章  >  web前端  >  js程式碼實作滑​​鼠拖曳div實例

js程式碼實作滑​​鼠拖曳div實例

小云云
小云云原創
2018-02-28 09:40:561623瀏覽

本文主要跟大家分享js程式碼實作滑​​鼠拖曳div實例,希望能幫助到大家。

直接上程式碼,簡單實用。

<!DOCTYPE HTML><html><head><meta charset="utf-8"><title></title> <script type="text/javascript" src=&#39;./js/jquery-1.8.3.min.js&#39;></script> <style type="text/css">#ptest{    width: 200px;    height: 200px;    background: red;    position: absolute;/*这很关键*/
    left: 40%;    top:37%;}#ptest:active{    cursor: move;}</style></head><body><p id="ptest">来,拖拽我啊~</p><script type="text/javascript">var opTest = document.getElementById("ptest");
darg(opTest);function darg(obj){
    //鼠标按下 
    obj.onmousedown = function(ev){

       //IE直接用event或者window.event得到事件本身,而在其他浏览器函数要获取到事件本身需要从函数中传入
      var oevent = ev || event;

      var distanceX = oevent.clientX - this.offsetLeft;
      var distanceY = oevent.clientY - this.offsetTop;        //鼠标移动
      document.onmousemove = function(ev){
        var oevent = ev || event;
        obj.style.left = oevent.clientX - distanceX + &#39;px&#39;;
        obj.style.top = oevent.clientY - distanceY + &#39;px&#39;; 
      };        //鼠标放开
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };  
}</script></body></html>

相關推薦:

jQuery使用drag效果實作自由拖曳div_jquery

以上是js程式碼實作滑​​鼠拖曳div實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn