簡單js實現div拖拽
程序员文章站
2022-05-24 09:12:23
...
css部分
#div1{
width: 300px;
height: 100%;
background-color: #ccc;
position: absolute;
}
hml部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="./index.css" />
<link rel="stylesheet" type="text/css" href="../cleardefault.css" />
<title>backvideo</title>
</head>
<body>
<video id="div1"></video>
<script src="./index.js"></script>
</body>
</html>
js部分
window.onload = function(){
var div1 = document.getElementById("div1");
div1.onmousedown = function(ev){
var oevent = ev || event;
var distanceX = oevent.clientX - div1.offsetLeft;
var distanceY = oevent.clientY - div1.offsetTop;
document.onmousemove = function(ev){
var oevent = ev || event;
div1.style.left = oevent.clientX - distanceX + 'px';
div1.style.top = oevent.clientY - distanceY + 'px';
};
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
};
}
}