Div position detection

I created a small game in which some blocks move around the main div. A mouse that also holds a div (I assigned a cursor position to this div).

I just want to keep track of whether the div cursor moves over the blocks (this is also a div). If this happens, the game will end.

How to determine if a block or div cursor moves with each other?

+3
source share
5 answers

If you use jQuery, you can find the left, top, width and height of the div using them:

$(myDiv).offset().left
$(myDiv).offset().top
myDiv.offsetWidth
myDiv.offsetHeight

Use those to work on the left, right, top and bottom of each div. Then two divs overlap with each other if:

left1 < right2 && left2 < right1 && top1 < bottom2 && top2 < bottom1
+4
source

, javascript, div , div.

, javascript, jQuery Prototype. , jQuery $(myDiv).offset() div .

jQuery UI div "", divs "Droppable", , Droppable over event, , div .

+1

, , .

, div, , , .

0

getBoundingClientRect()

: getBoundingClientRect -

0

jQuery, / ( LGPL); http://code.google.com/p/ra-ajax/source/browse/trunk/Ra/Js/Ra.js

- "" №. 220, "-" while.

;

var valueT = this.offsetTop  || 0;
var valueL = this.offsetLeft  || 0;
var el = this.offsetParent;

while (el) {
  Ra.extend(el, Ra.Element.prototype);
  if( el.tagName == 'BODY' ) {
    break;
  }
  var pos = el.getStyle('position');
  if( pos == 'relative' || pos == 'absolute') {
    break;
  }
  valueT += el.offsetTop  || 0;
  valueL += el.offsetLeft || 0;
  el = el.offsetParent;
}

"this" DOM...

, divs div : relative, ;

var y = parseInt(myElement.style.top, 10);
var x = parseInt(myElement.style.left, 10);

which will be an order of magnitude faster than performing "shift cycles" ...

0
source

Source: https://habr.com/ru/post/1704195/


All Articles