Home  >  Article  >  Web Front-end  >  js code to implement mouse dragging div instance

js code to implement mouse dragging div instance

小云云
小云云Original
2018-02-28 09:40:561678browse

This article mainly shares with you the js code to implement mouse dragging div examples, hoping to help everyone.

Directly upload the code, simple and practical.

<!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>

Related recommendations:

jQuery uses the drag effect to achieve free dragging div_jquery

The above is the detailed content of js code to implement mouse dragging div instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn