div drag

Online encountered an example of a div drag, only supports drag can not be resized,

There is a need to change the size can refer to another article: https://blog.csdn.net/vtopqx/article/details/89066771

Drag the code is as follows:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS拖拽div/title>
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
 #dv {
	width:100px;
	height:100px;
	background-color:blue;
	position:absolute;
}

</style>
</head>
<body>
<div id="test">
<div id="dv" class="list">0000</div>
</div>
<script>


//获取元素
var divId = 'dv';
var dv = document.getElementById(divId);
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
//鼠标按下事件
dv.onmousedown = function(e) {
    //获取x坐标和y坐标
    x = e.clientX;
    y = e.clientY;

    //获取左部和顶部的偏移量
    l = dv.offsetLeft;
    t = dv.offsetTop;
    //开关打开
    isDown = true;
    //设置样式  
    dv.style.cursor = 'move';
}
//鼠标移动
window.onmousemove = function(e) {
    if (isDown == false) {
        return;
    }
    //获取x和y
    var nx = e.clientX;
    var ny = e.clientY;
    //计算移动后的左偏移量和顶部的偏移量
    var nl = nx - (x - l);
    var nt = ny - (y - t);

    dv.style.left = nl + 'px';
    dv.style.top = nt + 'px';
}
//鼠标抬起事件
dv.onmouseup = function() {
    //开关关闭
    isDown = false;
    dv.style.cursor = 'default';
}
</script>

</body>
</html>

 

Published 327 original articles · won praise 566 · Views 2.63 million +

Guess you like

Origin blog.csdn.net/vtopqx/article/details/89067068