效果:
代码:
<!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>
body{
display: flex;
align-items: center;
justify-content: center;
}
#father {
width: 500px;
height: 500px;
background-color: #acf31f;
position: relative;
}
#son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
transition: all linear 0.5s;
}
</style>
</head>
<body>
<div id="father">
<div id="son"></div>
</div>
<script>
const father = document.getElementById("father")
let fatherClientWidth = father.clientWidth
let fatherClientHeight = father.clientHeight
const son = document.getElementById("son")
let sonClientWidth = son.clientWidth
let sonClientHeight = son.clientHeight
father.addEventListener("click",(event)=>{
let mouseX = event.offsetX
let mouseY = event.offsetY
let positionX = mouseX
let positionY = mouseY
if((mouseX + sonClientWidth)>fatherClientWidth){
positionX = mouseX - sonClientWidth
}
if((mouseY + sonClientHeight)>fatherClientHeight){
positionY = mouseY - sonClientHeight
}
son.style.left = positionX + "px"
son.style.top = positionY + "px"
})
</script>
</body>
</html>
新建html复制粘贴就可以,看懂了这个组件封装就很简单了——