例:
<div id="big"> </div>
<div class="small"> </div>
<div class="small"> </div>
<div class="small"> </div>
<div class="small"> </div>
<div class="small"> </div>
<!-- ...and so on -->
Run Code Online (Sandbox Code Playgroud)
"#big"绝对位于".small"的一部分后面,但不是父元素.
我一直这样做:
var smallArray = [];
var $big = $('#big');
var $bigPos = $big.offset();
$('div.small').each(function() {
var $this = $(this);
var $thisPos = $this.offset();
if(
$thisPos.left >= $bigPos.left &&
$thisPos.left <= $bigPos.left+$big.outerWidth() &&
$thisPos.top >= $bigPos.top &&
$thisPos.top <= $bigPos.top+$big.outerHeight()
) smallArray.push($this);
});
Run Code Online (Sandbox Code Playgroud)
......但这似乎很糟糕.我是否错过了一些jQuery或vanilla JavaScript的方法,这些方法可以让我以更优雅高效的方式做到这一点?
非常感谢您提供的任何帮助.
cmc*_*loh 21
此公式将检测是否有任何指定元素与目标元素重叠:
function findIntersectors(targetSelector, intersectorsSelector) {
var intersectors = [];
var $target = $(targetSelector);
var tAxis = $target.offset();
var t_x = [tAxis.left, tAxis.left + $target.outerWidth()];
var t_y = [tAxis.top, tAxis.top + $target.outerHeight()];
$(intersectorsSelector).each(function() {
var $this = $(this);
var thisPos = $this.offset();
var i_x = [thisPos.left, thisPos.left + $this.outerWidth()]
var i_y = [thisPos.top, thisPos.top + $this.outerHeight()];
if ( t_x[0] < i_x[1] && t_x[1] > i_x[0] &&
t_y[0] < i_y[1] && t_y[1] > i_y[0]) {
intersectors.push($this);
}
});
return intersectors;
}
Run Code Online (Sandbox Code Playgroud)
这个问题非常有助于解决这个问题.
| 归档时间: |
|
| 查看次数: |
8957 次 |
| 最近记录: |