gpt4 book ai didi

javascript - 单独检测共享同一类的元素

转载 作者:行者123 更新时间:2023-11-30 12:52:02 25 4
gpt4 key购买 nike

我有三个 div (.block)。每个都应该变成红色,这取决于另一个 div (.square) 是否位于其顶部。到目前为止,只有一个“.square”被识别(标记中列出的第一个),并且它将所有“.block”变成红色,而不仅仅是它上面的那个。此外,我们将不胜感激有关使它更干的任何提示。

这是我的代码-

var squareWidth = $('.square').width();
var squareHeight = $('.square').height();
var squareLeft = $('.square').offset().left;
var squareTop = $('.square').offset().top;
var squareRight = squareLeft + squareWidth;
var squareBottom = squareTop + squareHeight;

$('.block').each(function() {

var blockWidth = $(this).width();
var blockHeight = $(this).height();
var blockLeft = $(this).offset().left;
var blockTop = $(this).offset().top;
var blockRight = blockLeft + blockWidth;
var blockBottom = blockTop + blockHeight;

if(squareLeft > blockLeft && squareRight < blockRight && squareTop > blockTop
&& squareBottom < blockBottom) {

$('.block').css('background', 'red');
}
});

这是我的 fiddle :http://jsfiddle.net//QmE98/

最佳答案

使用 this 来引用正在检查的 .block 的特定实例:

if(squareLeft > blockLeft && squareRight < blockRight && squareTop > blockTop 
&& squareBottom < blockBottom) {

$(this).css('background', 'red');
}

要更加抽象您的代码,请改用 CSS 类切换:

    $(this).addClass('myClass');

更新:由于您的 HTML 的结构方式,我们必须按索引引用元素:

http://jsfiddle.net/isherwood/QmE98/10

$('.block').each(function () {
// deduct the quantity of .square elements
var myIndex = $(this).index() - $('.square').size();

var squareWidth = $('.square').eq(myIndex).width();
var squareHeight = $('.square').eq(myIndex).height();
var squareLeft = $('.square').eq(myIndex).offset().left;
var squareTop = $('.square').eq(myIndex).offset().top;
...

if (squareLeft > blockLeft && squareRight < blockRight && squareTop > blockTop && squareBottom < blockBottom) {
$(this).css('background', 'red');
}
});

但是,如果您可以对 HTML 进行一些适度的重组,那就更好了:

http://jsfiddle.net/isherwood/QmE98/5

<div class="container">
<div class="block"><div style="top: 30px; left: 30px" class="square"></div></div>
<div class="block"><div style="top: 30px; left: 150px" class="square"></div></div>
<div class="block"><div style="top: 30px; left: 320px" class="square"></div></div>
</div>

关于javascript - 单独检测共享同一类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20618660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com