简体   繁体   中英

How to trigger an event when elements (divs, images) touch each other?

I would like to know if it is at all possible to trigger a jquery event (showing contents of a ) when an element (an image) touches, enters, passes over etc. another element (a div containing another image).

I am playing around making a stupid little game using only Javascript, CSS, and HTML, and I'm trying to figure out how to deploy an event, just like .click(), or any other when the character(the image) touches or enters over another element(a div with an image in it). I got the character (an image element) to move around using w, a, s, d and I want it to trigger events when it touches something.

I have to make some assumptions here. You have object A, which is moving with wasd keys, and you have objects B and C. You already have an event which listens for wasd key press and moves object A. After you move object A, you need to calculate the bounds of A (left, right, top, bottom) and compare with the bounds of object B and object C.

You can use $element.offset() to get the left and top, then right is left + width and bottom is top + height.

So once you have that for all objects, object intersect:

aTopOverlap = a.top > b.top && a.top < b.bottom;
aBottomOverlap = a.bottom > b.top && a.bottom < b.bottom;
aLeftOverlap = a.left > b.left && a.left < b.right;
aRightOverlap = a.right > b.left && a.right < b.left;
aVerticalOverlay = b.top > a.top && b.bottom < a.bottom;
aHorizontalOverlay = b.left > a.left && b.right < a.right;

if ((aTopOverlap || aBottomOverlap || aVerticalOverlay) && (aLeftOverlap || aRightOverlap || aHorizontalOverlay)) {
    //collision logic here
}

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