<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0px;
height: 0px;
box-sizing: border-box;
}
#box {
position: absolute;
background-color: #d38383;
width: 200px;
height: 200px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box = document.getElementById("box")
box.onmousedown = function (d) {
let offsetX = d.offsetX
let offsetY = d.offsetY
document.onmousemove = function (e) {
console.log(e)
let _left = e.clientX
let _top = e.clientY
top1 = _top - offsetY
left2 = _left - offsetX
if (top1 < 1) {
top1 = 0
}
if (left2 < 0) {
left2 = 0
}
if (left2 > 1585 - offsetX)
{
left2 = 1585-offsetX
}
if(top1>970-offsetY)
{
top1=970-offsetY
}
box.style.left = left2 + 'px'
box.style.top = top1 + 'px'
}
document.onmouseup = function () {
document.onmousemove = null
}
}
</script>
</body>
</html>
实践总结:该代码考验了js的运用;其中用clientx,clienty,来找出鼠标到浏览器的距离;用offsetx,offsety,来找出鼠标在div中的距离;通过clientx-offsetx;clienty-offsety来确定div在浏览器中的位置,用function(e)和console.log来查找数值防止div超出网页;并学习了一个新效果
class+.style+.css类型="效果名称"代码中给出的是box.style.left=left2+'px'和position:absolute;以网页为父标签的绝对定位来实时确定div在网页中的位置;