作業(yè)分析
本次使用html與js樣式編寫效果如下

屏幕截圖 2025-03-26 200908.png

屏幕截圖 2025-03-26 200855.png
代碼實現(xiàn)
使用html代碼實現(xiàn)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鼠標拖拽</title>
<style>
#box{
width: 300px;
height: 200px;
background-color:olivedrab;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
//獲取標簽對象
let box = document.getElementById("box")
//1按下鼠標,獲取offsetx/offsety
box.onmousedown = function(e){
let ox =e.offsetX
let oy =e.offsetY
//2鼠標在網(wǎng)頁中移動(包含在1里面)
document.onmousemove = function(e2){
//獲取鼠標在窗口的位置
let cx = e2.clientX
let cy = e2.clientY
//計算left 和 top
let _left = cx - ox
let _top = cy - oy
if(_left<0){
_left=0
}
if(_top<0){
_top=0
}
if(_top>document.documentElement.clientHeight - box.offsetHeight){
_top=document.documentElement.clientHeight - box.offsetHeight
}
if(_left>document.documentElement.clientWidth - box.offsetWidth){
_left = document.documentElement.clientWidth - box.offsetWidth
}
//給div設置位置
box.style.left = _left +"px"
box.style.top = _top + "px"
}
}
//3 和1事件對等,網(wǎng)頁中松開鼠標-停止移動
document.onmouseup = function(){
//停止移動
document.onmousemove = null
}
</script>
</body>
</html>