简体   繁体   中英

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. 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.

 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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