效果:
代码:
<!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.clientWidthlet fatherClientHeight = father.clientHeightconst son = document.getElementById("son")let sonClientWidth = son.clientWidthlet sonClientHeight = son.clientHeightfather.addEventListener("click",(event)=>{let mouseX = event.offsetXlet mouseY = event.offsetYlet positionX = mouseXlet positionY = mouseYif((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复制粘贴就可以,看懂了这个组件封装就很简单了——