jQuery(document).ready(function(){
var insertionTemplate = jQuery(".hiddenAdBox").eq(0).html(),
insertionTarget = jQuery('ul'),
insertionTargetChildren = insertionTarget.find('li'),
insertionFrequency = 2;
var random;
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
insertionTargetChildren.eq(random).after(insertionTemplate);
}
});
我有项目列表,还需要在刷新页面时随机显示广告。现在,当广告数量为2(insertionFrequency = 2
)时,有一段时间它们出现在彼此附近,但不应该如此。如何检测它并且不要让广告彼此靠近?
答案 0 :(得分:1)
要阻止广告水平,您可以按以下方式执行:
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
if(insertionTargetChildren.eq(random).next('.placeforad').length || insertionTargetChildren.eq(random).prev('.placeforad').length)
//check whether its previous li or next li has ad with class .placeforad
{
i--; //decrease the count so as to come up with separate random number
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
}
<强> DEMO 强>
但是对于垂直预防,因为你在每行中没有相同数量的正方形,例如第1行和第2行有3个块而最后一行只有2个,所以棘手识别水平。如果有相同数量的正方形,那么也可以采取一些方法来实现这一目标。
<强>更新强>
由于您同意连续获得3个区块,因此以下代码将避免广告水平以及垂直
小 DEMO
for (var i = 0; i < insertionFrequency; i++) {
random = Math.floor(Math.random() * insertionTargetChildren.length) + 0;
var currentElement=insertionTargetChildren.eq(random);
var addedElement=$('li.placeforad:visible');
if(currentElement.next('.placeforad').length || currentElement.prev('.placeforad').length)
{
i--;
}
else
{
if(i!=0)
{
if(addedElement.index() > currentElement.index() &&
(addedElement.index() - currentElement.index())==3)
{
i--;
}
else if(currentElement.index() - (addedElement.index()-1)==3)
{
i--;
}
else
{
insertionTargetChildren.eq(random).after(insertionTemplate);
}
}
else
insertionTargetChildren.eq(random).after(insertionTemplate);
}
}