我有三个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');
}
});
这是我的小提琴:http://jsfiddle.net//QmE98/
答案 0 :(得分:3)
使用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>
答案 1 :(得分:0)
工作。改变了一些事情 -
var squareWidth = $('。square')。width(); var squareHeight = $('。square')。height();
$('.block').each(function() {
var squareLeft = $(this).children('.square').offset().left;
var squareTop = $(this).children('.square').offset().top;
var squareRight = squareLeft + squareWidth;
var squareBottom = squareTop + squareHeight;
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) {
$(this).css('background', 'red');
}
});