2017-11-16 2 views
1

나는 게임을 만들고 있는데 canvas 대신 올바른 div를 사용하고 있습니다. 올바른 div는 한 div가 항상 다른 div의 안에 있어야합니다. 이런 식으로 테스트 스크립트를 만들 때이 문제가 발생했습니다. 한 사업부가 다른 사업부 외부에 있는지 어떻게 알 수 있습니까?

마우스가 큰 녹색 사업부 위에있을 때 코드는 마우스 X와 마우스 Y를 감지

 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>
은, 그것은 마우스 X와 마우스 Y. 내 문제에 흰색 사업부의 왼쪽 모서리를두고 내 마우스가 흰색 div를 아래로 드래그하거나 오른쪽으로 드래그하면 녹색 div에서 드래그 할 수 있습니다.

이 문제를 해결할 수있는 방법이 있습니까?

+0

당신은 부모 요소에 Element.getBoundingClientRect()를 호출하고 mousex/쥐의 너비/높이 – jcubic

+0

다음 왼쪽/상단보다 더 적은 경우에 확인하실 수 있습니다 https://codepen.io/piotrazsko/pen/VrrZBq –

+0

재귀 사용을 권장하지 않습니다. 고성능을 위해 루프를 사용하십시오. –

답변

0

나는이 작업을 간단하고 이해하기 쉬운 방법으로 생각했습니다.

testdiv의 너비, 높이, x, y, x 오프셋 (offset)에 대한 변수를 마우스와 마우스에서 y 오프셋으로 만들었습니다.

var divw = 50; 
var divh = 50; 

var divofx = 25; 
var divofy = 25; 

그런 다음 도시 divs 폭에 대한 변수를 만들었습니다.

var cityw = 500; 

그런 다음 화면의 중심을 찾기 위해 screen.width/2를 사용했습니다.

var centerx = screen.width/2; 

그럼, 메인 함수에 아래의 코드를 넣어 언제든지 변경 testdiv의 크기를 만든 :

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

그런 다음 나는 도시의 가장자리를 찾기 위해 폭 변수를 사용 div.

그런 다음 가장자리를 기반으로 간단한 if 충돌 탐지 if 문을 만들었습니다. 나는 또한 예쁜 멍청이가 그대로 남아 있기 때문에 Y mutch를 바꿀 필요가 없었다.

 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); 

지금 전체 프로그램과 같이 보인다 :

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

현재 JS에 지원되는 상위 선택자가 없으므로

당신은 JQuery와 또는 CSS를 사용할 수 있습니다 중 하나, 나는 자바 스크립트 옵션 및 CSS 옵션을 모두 나열하고

  1. 옵션 1 : 앞에는 어떤 ParentElement 요소에 맞게 Sibling Combination : $("a.active").parents('li').css("property", "value");
  2. 옵션 2 ChildElement 요소 새 위치는 외부 당신이 원하는 곳의 경우

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

+0

jQuery를 사용하지 않는 것을 선호하므로이 옵션을 사용할 수 없습니다. 또한 내가 제공 한 두 번째 옵션을 이해하지 못합니다. 명확히 해 주시겠습니까? – 360gamegod

+0

위의 div 관계를 사용하여 div를 선택하려면'css '를 사용할 수 있습니다 .. 링크를 클릭하면 더 많은 예제가 표시됩니다 – transformer

0

당신은 자식 DIV 위치를 변경하기 전에 검사를 할 수 있습니다, 당신은 그것을 건너 뛸 수 있습니다. 당신이 할 수있는

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

이 코드를 시도 :

뭔가 같은

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); 
} 

을 그리고 당신은 폭의 값과 높이 CSS를 픽셀을 추가해야합니다

#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; 
      } 

그리고 youre 코드가 더 빠르기 때문에 항상 변수 노드에 노드를 저장합니다. 변수 테스트를 위해 변수 i를 사용합니다. 다른 솔루션을 사용할 수 있습니다. 다음 앱을 만들었습니다 : https://codepen.io/piotrazsko/pen/VrrZBq

+0

"let i = 0"과 "if (i === 100) {return; " 놀이? – 360gamegod

+0

이것은 testdiv 함수에서 반환됩니다. –

관련 문제