Home  >  Article  >  Web Front-end  >  Example of method to implement drag and drop event in js

Example of method to implement drag and drop event in js

小云云
小云云Original
2018-03-20 17:09:471510browse


This article mainly shares with you examples of methods of implementing drag and drop events in js, hoping to help everyone.

HTML

<body> 
     <p></p></body>

CSS

p{        position: absolute;        width: 200px;        height: 200px;        background: #369
    }

JS

window.onload = function(){
    var op = document.getElementsByTagName("p")[0];

    /*鼠标点击的位置距离p左边的距离 */
    var disX = 0;
    /*鼠标点击的位置距离p顶部的距离*/
    var disY = 0;
    op.onmousedown = function(){
        var e = e || window.event;
        disX = e.clientX - op.offsetLeft;
        disY = e.clientY- op.offsetTop;

        document.onmousemove = function(e){
            var e = e || window.event;
            // 横轴坐标
            var leftX = e.clientX - disX;
            // 纵轴坐标
            var topY =e.clientY - disY;

            if( leftX < 0 ){
                leftX = 0;
            }            /* 获取浏览器视口大小 document.document.documentElement.clientWidth*/
            else if(  leftX > document.documentElement.clientWidth - op.offsetWidth ){
                leftX = document.document.documentElement.clientWidth - op.offsetWidth;
            }

            if( topY < 0 ){
                topY = 0;
            }
            else if( topY > document.documentElement.clientHeight -op.offsetHeight ){
                topY = document.documentElement.clientHeight - op.offsetHeight;
            }
            op.style.left = leftX + "px";
            op.style.top = topY+"px";
        }
        document.onmouseup = function(){
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
 }

Related recommendations:

html drag drag event

JavaScript mouse drag event implementation case

HTML5 explanation of drag events dragstart, drag and dragend

The above is the detailed content of Example of method to implement drag and drop event in js. 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