style部分
* {
margin: 0;
padding: 0;
}
.app {
//可自定义样式
/* margin: auto; */
width: 300px;
height: 300px;
background: rgb(175, 175, 175);
position: absolute;
/* border: 1px solid red; */
text-align: center;
line-height: 300px;
font-size: 20px;
color: red;
font-weight: bolder;
}
html部分
<div class="app">
</div>
js部分
let canMove = false
var app = document.querySelector(".app")
app.onmousedown = function (e) {
canMove = true
x = e.pageX - app.offsetLeft
y = e.pageY - app.offsetTop
}
window.onmouseup = function (e) {
canMove = false
}
window.onmousemove = function (e) {
e.preventDefault(); //阻止默认行为
if (canMove) {
let left = e.pageX - x
let top = e.pageY - y
if (left < 0) left = 0
if (top < 0) top = 0
let maxLeft = window.innerWidth - app.offsetWidth
let maxTop = window.innerHeight - app.offsetHeight
if (left > maxLeft) left = maxLeft
if (top > maxTop) top = maxTop
app.style.left = left + "px"
app.style.top = top + 'px'
}
}
}
app.oncontextmenu = function (e) {
e.preventDefault();
//阻止默认事件
}
window.onblur = function () {
canMove = false
}