<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
#box {
width: 300px;
height: 300px;
background: lightgray;
position: absolute;
}
#box2 {
width: 100%;
height: 50px;
line-height: 50px;
background: pink;
text-align: center;
font-size: 23px;
user-select: none;
}
</style>
</head>
<body>
<div id="box">
<div id="box2">zhuzhuxia</div>
</div>
<script>
let winW = document.documentElement.clientWidth,//整个屏幕的宽度
winH = document.documentElement.clientHeight,//整个屏幕的高度
box = document.getElementById('box');//盒子
box.style.position = 'absolute';//给box相对定位----让盒子水平垂直居中
box.style.left = (winW - 300) / 2 + 'px';//整个屏幕的宽度-自身宽度/2
box.style.top = (winH - 300) / 2 + 'px';//整个屏幕的高度-自身高度/2
/* box.style.left = (winW - box.offsetWidth) / 2 + 'px';
box.style.top = (winH - box.offsetHeight) / 2 + 'px'; */
//
function move(e) {//只要鼠标移动
//获光标最新left值
let clientX = e.clientX;
let clientY = e.clientY;
//给box设置最新的left和top即可---最新-旧的+left(起始)
box.style.left = clientX - this.initClientX + this.initLeft + "px";
box.style.top = clientY - this.initClientY + this.initTop + "px";
}
function up() {
window.onmousemove = null;//出来不动
}
function down(e) {//在鼠标按下时候,会把当前起始的box的left值和光标的
//clientX值保存
this.initLeft = parseFloat(box.style.left);//把初始的left值保存到title身上
this.initTop = parseFloat(box.style.top);
this.initClientX = e.clientX;//初始值
this.initClientY = e.clientY;
window.onmousemove = move.bind(box2);//括号里写this也行
}
box2.onmousedown = down;
window.onmouseup = up;
</script>
</body>
</html>
鼠标放上去拖拽2
最新推荐文章于 2023-02-01 08:05:55 发布