简体   繁体   English

如何在不超出父级的情况下让 div 内的元素跟随 cursor?

[英]How do I get an element inside a div to follow the cursor without going outside the parent?

I'm trying to make a div follow the cursor in a parent div, and I got it semi working, but it keeps going outside of the parent div slightly on the right side and on the bottom side of the parent div.我正在尝试让一个 div 跟随父 div 中的 cursor ,我让它半工作,但它在父 div 的右侧和底部稍微离开父 div。 I tried to make an if statement for if it goes above an x/y position then it has to stop, but that didn't work.我试图做一个 if 语句,如果它超过 x/y position 然后它必须停止,但这没有用。

 var shipp = document.getElementById("spaceship"); document.getElementById("ship-container").addEventListener("mousemove", function(e) { e = e || window.event; e.preventDefault(); var x = e.clientX; var y = e.clientY; shipp.style.left = x + "px"; shipp.style.top = y + "px"; document.getElementById("disp").innerHTML = "X:" + x + " Y:" + y; });
 <p style="color: white;" id="disp"></p> <div class="ship" id="ship-container"> <div class="spaceship" id="spaceship"><img class="spaceship-img" src="https://i.ibb.co/27443m1/spaceship.png" alt="spaceship"></div> </div> <p style="color: white;" id="disp"></p>

Here is the codepen to show how it keeps going outside of the parent div: https://codepen.io/metmouse/pen/rNxRymP这是显示它如何在父 div 之外继续运行的代码笔: https://codepen.io/metmouse/pen/rNxRymP

You are missing "position: relative" on element which 'left' and 'top' you are actually modifying:您实际上正在修改的“左”和“上”元素缺少“位置:相对”:

 var shipp = document.getElementById("spaceship"); document.getElementById("ship-container").addEventListener("mousemove", function(e) { e = e || window.event; e.preventDefault(); var x = e.clientX; var y = e.clientY; shipp.style.left = x + "px"; shipp.style.top = y + "px"; document.getElementById("disp").innerHTML = "X:" + x + " Y:" + y; });
 <p style = "color: black;" id = "disp"></p> <div class = "ship" id = "ship-container"> <div style="position:relative" class = "spaceship" id = "spaceship"><img class = "spaceship-img" src = "https://i.ibb.co/27443m1/spaceship.png" alt = "spaceship"></div> </div>

Not sure if this is the desired effect, though.不过,不确定这是否是预期的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM