首先对我的问题的共谋感到抱歉!
我有一个随机动画,使所有图像以不同的不透明度显示。其中一些位于 h1 标签下方。因此 h1 标签下的所有图像都不应该有动画效果。
目前我只有随机函数在工作:
(function fadeInDiv() {
var divs = $('li');
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
最佳答案
尝试根据 h1 的相对垂直位置(.display
div 的高度为零),使用过滤器
来减少可选择的项目。我检查这些项目是否与标题完全重叠并排除它们:
例如
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
return top > h1bottom || bottom < h1top;
});
JSFiddle:http://jsfiddle.net/TrueBlueAussie/G25fT/5/
(function fadeInDiv() {
// exclude any divs
var $heading = $('.heading h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
//console.log("top="+ h1top + " bottom = " + h1bottom);
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
return top > h1bottom || bottom < h1top;
});
//console.log("Len=" + divs.length);
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
更新:
如果您想删除调整大小时的样式(当项目从标题下移出时)
JSFiddle:http://jsfiddle.net/TrueBlueAussie/G25fT/11/
// Get the divs that should change
function displayThese() {
var $heading = $('.heading h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
//console.log("top="+ h1top + " bottom = " + h1bottom);
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
return top > h1bottom || bottom < h1top;
});
return divs;
}
(function fadeInDiv() {
// exclude any divs
var divs = displayThese();
//console.log("Len=" + divs.length);
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: .3
});
});
关于javascript - 如果位于另一个元素下方,则 Jquery 随机动画不应该发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187566/