Home >Web Front-end >JS Tutorial >How do you detect collisions between jQuery `` elements?
Collision Detection between jQuery Div Elements
Detecting collisions between elements is a fundamental task in many web applications. In this case, the objective is to determine if two specific
One effective approach to tackle this problem is to leverage the overlaps function provided below:
var overlaps = (function () { function getPositions( elem ) { var pos, width, height; pos = $( elem ).position(); width = $( elem ).width(); height = $( elem ).height(); return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ]; } function comparePositions( p1, p2 ) { var r1, r2; r1 = p1[0] < p2[0] ? p1 : p2; r2 = p1[0] < p2[0] ? p2 : p1; return r1[1] > r2[0] || r1[0] === r2[0]; } return function ( a, b ) { var pos1 = getPositions( a ), pos2 = getPositions( b ); return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] ); }; })();
This function takes two
To demonstrate the usage of this function, you can create a set of
$(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 ); });
In this example, a red box named "Red box" is created and moved around using the mouse. Several other boxes labeled "Box 1" to "Box 4" are positioned at different locations in the "area" div. The jQuery script checks for collisions between the "Red box" and each of the other boxes and displays the results in a series of
elements.
By utilizing the overlaps function, you can effectively implement collision detection for jQuery
The above is the detailed content of How do you detect collisions between jQuery `` elements?. For more information, please follow other related articles on the PHP Chinese website!