前端界面拖拽
html代碼
<div id='ai'></div>
js代碼
function dragFunc(id) {
var Drag = document.getElementById(id);
Drag.onmousedown = function(event) {
var ev = event || window.event;
event.stopPropagation();
var disX = ev.clientX - Drag.offsetLeft;
var disY = ev.clientY - Drag.offsetTop;
document.onmousemove = function(event) {
var ev = event || window.event;
Drag.style.left = ev.clientX - disX + "px";
Drag.style.top = ev.clientY - disY + "px";
Drag.style.cursor = "move";
};
};
Drag.onmouseup = function() {
document.onmousemove = null;
this.style.cursor = "default";
};
};
dragFunc("ai");
HTML示例(複製代碼,後綴設置爲.html,直接運行測試)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>前端拖拽</title>
<style>
body {
margin: 10px;
}
#ai {
position: absolute;
width: 500px;
height: 400px;
border: 2px solid #92cccc;
border-radius: 10px;
background: rgba(0, 0, 0, 0.5);
z-index: 1000px;
}
</style>
</head>
<body>
<div id='ai'></div>
<script>
function dragFunc(id) {
var Drag = document.getElementById(id);
Drag.onmousedown = function(event) {
var ev = event || window.event;
event.stopPropagation();
var disX = ev.clientX - Drag.offsetLeft;
var disY = ev.clientY - Drag.offsetTop;
document.onmousemove = function(event) {
var ev = event || window.event;
Drag.style.left = ev.clientX - disX + "px";
Drag.style.top = ev.clientY - disY + "px";
Drag.style.cursor = "move";
};
};
Drag.onmouseup = function() {
document.onmousemove = null;
this.style.cursor = "default";
};
};
dragFunc("ai");
</script>
</body>
</html>