简体   繁体   中英

How Can I Detect If One Div Is Outside Another Div?

I am making a game and I am using div's instead of canvas.rect's and I want one div to always be inside of another div. I ran into this problem when I made a test script that looked like this.

 var mousex, mousey; function mousepos(e){ mousex = e.clientX; mousey = e.clientY; document.getElementById("xy").innerText = mousex + " , " + mousey; } function testdiv(){ document.getElementById("testdiv").style.left = mousex; document.getElementById("testdiv").style.top = mousey; setTimeout(testdiv, 30); }
 #city{ border: 1px dotted white; background-color: lightgreen; height: 500; width: 500; resize: both; overflow: hidden; max-height: 500px; max-width: 500px; min-height: 100px; min-width: 100px; } #xy{ color: white; } #testdiv{ background-color: white; position: absolute; width: 100px; height: 100px; } #body{ background-color: black; }
 <body id="body" onload="testdiv()"> <center> <div id="city" onmousemove="mousepos(event);"> <div id="testdiv"></div> </div> <p id="xy"></p> </center> </body>

The code detects your mouse X and mouse Y when your mouse is over the big green div, then it puts the white div's left corner on your mouse X and mouse Y. My problem is that when my mouse is draging the white div down or right, I can drag it off of the green div.

Is there a way I could fix this problem?

Since there are no supported parent selectors in the current JS.

You could either use Jquery or CSS, I am listing both Javascript options, and CSS options

  1. Option 1: $("a.active").parents('li').css("property", "value");
  2. Option 2: Sibling Combination to match any ParentElement element that is preceded by an ChildElement element.

    // Just change the parent and child elemets below ParentElement ~ ChildElement { property: value; }

You can make a check before changing the child div position, if its new position is outside of where you want it to be, you can skip it.

Something like:

if (mouse.x > parent_div_width){
    return;
}
else {
   child_div_Xpos = mouse.x
}

You can to try this code:

  var mousex, mousey;

function mousepos(e) {
    mousex = e.clientX;
    mousey = e.clientY;
    document.getElementById("xy").innerText = mousex + " , " + mousey;
}
var coordCity = document.getElementById("city").getBoundingClientRect();
var elem = document.getElementById("testdiv");
let i = 0

function testdiv() {
    elem.style.left = mousex + 'px';
    elem.style.top = mousey + 'px';
    var coord = elem.getBoundingClientRect();
    if(coord.left < coordCity.left ||
      coord.right > coordCity.right ||
      coord.bottom > coordCity.bottom || 
      coord.top < coordCity.top) {
      console.log('rect is out');
    };
    i++;
    if(i === 100) {
        return;
    }
    setTimeout(testdiv, 50);
}

And you need add in css px to value of width and height:

#city{
            border: 1px dotted white;
            background-color: lightgreen;
            height: 500px;
            width: 500px;
            resize: both;
            overflow: hidden;
            max-height: 500px;
            max-width: 500px;
            min-height: 100px;
            min-width: 100px;
          }

And always save youre nodes to variable, because it does youre code faster, I use variable i for stop test. You can use another solution. I created next app: https://codepen.io/piotrazsko/pen/VrrZBq

I figured out a simple, more understandable way to do this.

I created a variables for the testdiv's width, height, x, y, x offset from mouse, and y offset from mouse.

var divw = 50;
var divh = 50;

var divofx = 25;
var divofy = 25;

Then I made a variable for the city divs width.

var cityw = 500;

Then, I used screen.width / 2 to find the center of the screen.

var centerx = screen.width / 2;

Then, I made the size of the testdiv changeable at any time by putting the code below into the main function :

document.getElementById("testdiv").style.width = divw;
document.getElementById("testdiv").style.height = divh;

Then I used the width variable to find the edges of the city div.

Then, based off of the edges, I made some simple collision detecting if statements. I also did not need to change the Y mutch since it pretty mutch stays the same.

        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);

Now the whole program looks like:

<html>

  <head>

    <style>

      #city{
        border: 1px dotted white;
        background-color: lightgreen;
        height: 500;
        width: 500;
        overflow: none;
        max-height: 500px;
        max-width: 500px;
        min-height: 100px;
        min-width: 100px;
      }
      #xy{
        color: white;
      }
      #testdiv{
        background-color: white;
        position: absolute;
        width: 100px;
        height: 100px;
      }
      #body{
        background-color: black;
      }

    </style>
    <script>

    var mousex, mousey;
    var divw = 50;
    var divh = 50;
    var divofx = 25;
    var divofy = 25;
    var cityw = 500;

      function mousepos(e){
        mousex = e.clientX - divofx;
        mousey = e.clientY - divofy;
        document.getElementById("xy").innerText = mousex + " , " + mousey;
      }

      function testdiv(){
        var centerx = screen.width / 2;

        document.getElementById("city").style.width = cityw;
        document.getElementById("testdiv").style.width = divw;
        document.getElementById("testdiv").style.height = divh;

        if(mousex + divw > centerx + (cityw / 2)){
          mousex = centerx + (cityw / 2) - divw;
        }
        else{
          document.getElementById("testdiv").style.left = mousex;
        }
        if(mousey > (cityw - divh) + 10){
          mousey = (cityw - divh) + 10;
        }
        else{
          document.getElementById("testdiv").style.top = mousey;
        }
        if(mousex < centerx - cityw / 2){
          mousex = centerx - cityw / 2;
        }
        if(mousey < 8){
          mousey = 8;
        }
        setTimeout(testdiv, 1);
      }

    </script>

  </head>

  <body id="body" onload="testdiv()" onmousemove="mousepos(event);">

    <center>
      <div id="city" onmousemove="mousepos(event);">
        <div id="testdiv"></div>
      </div>

      <p id="xy"></p>
    </center>

  </body>

</html>

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