Knowing when two elements have overlapped is essential for various interactive web applications. Imagine a simple game where two colored boxes move perpendicularly on a grid. To determine whether the red box has collided with any of the other boxes, you can employ the following jQuery/JavaScript solution:
getPositions: Retrieves the position and dimensions of an element.
comparePositions: Compares the ranges of two given positions and returns true if they overlap or touch.
overlaps: The main function checks for overlap between two elements. It uses getPositions and comparePositions to determine if any of their axes overlap.
Consider the HTML structure:
<div>
And the corresponding JavaScript:
var overlaps = (function () { // ... same as before ... })(); $(function () { var area = $('#area')[0], box = $('#box0')[0], html; html = $('#area').children().not(box).map(function (i) { return '<p>Red box + Box ' + (i + 1) + ' = ' + overlaps(box, this) + '</p>'; }).get().join(''); $('body').append(html); });
This script appends messages to the page indicating whether the red box overlaps with any of the other boxes.
The above is the detailed content of How to Detect Collisions Between Elements in jQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!