<style>
* {
padding: 0;
margin: 0;
}
.demo {
width: 300px;
height: 300px;
background-color: #DD5246;
position: absolute;
}
</style>
<div class="demo"></div>
<script>
let canMove = false;
var demo = document.querySelector('.demo')
let x = 0, y = 0;
demo.onmousedown = function (e) {
x = e.pageX - demo.offsetLeft;
y = e.pageY - demo.offsetTop;
canMove = true;
}
window.onblur = function () {
canMove = false;
}
window.onmouseup = function () {
canMove = false;
}
demo.oncontextmenu = function (e) {
e.preventDefault()//阻止默认行为
console.log('邮件里');
}
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 - demo.offsetWidth
let maxTop = window.innerHeight - demo.offsetHeight
if (left > maxLeft) let = maxLeft
if (top > maxTop) top = maxTop
demo.style.left = left + 'px'
demo.style.top = top + 'px'
}
}
</script>
js DOM练习
最新推荐文章于 2022-11-04 13:00:00 发布