![](/img/trans.png)
[英]Bootstrap affix with custom JS and CSS overlapping HTML elements/positioned incorrectly
[英]Overlapping elements - HTML, CSS, and jQuery
我有重疊的元素,我想防止這種情況發生。 這是一張圖片: http://grab.by/cB7t
此外,這里是這些元素的 CSS:
.navigationItem {
background: #808080;
-webkit-border-radius: 360px;
padding: 1.0em;
text-decoration: none;
color: #fff;
position: absolute;
-webkit-box-shadow: 0px 2px 5px #909090;
font-weight: bold;
text-shadow: 1px 1px 2px #707070;
font-size: 1.0em;
}
它們位於 HTML 中:
<a href="#" class="navigationItem" id="nav0">play</a>
<a href="#" class="navigationItem" id="nav1">register</a>
<a href="#" class="navigationItem" id="nav2">our blog</a>
<a href="#" class="navigationItem" id="nav4">contact us</a>
<a href="#" class="navigationItem" id="nav5">about us</a>
<a href="#" class="navigationItem" id="nav6">our rules</a>`
如您所見,我將它們用作使用 HTML 標記a
簡單樣式鏈接。 它們的位置是絕對的原因是因為我正在使用 jQuery 移動它們:
function moveAll() {
for(var i = 0; i < AMOUNT; i++) {
var random = Math.random() * 500;
$("#nav" + i).animate({"left": random + i + "px"}, "slow");
$("#nav" + i).animate({"top": random + i + "px"}, "slow");
}
}
但是,當它們移動時,它們有時會重疊,這很煩人。 如何防止它們重疊? 感謝你付出的努力。
刪除position:absolute
將使它們並排呈現。
但是,如果重點是將它們隨機分散,那么您將必須跟蹤定位的元素並在計算它們的 position 時將其考慮在內。 您應該保存每個鏈接的 position 並根據之前已經定位的鏈接計算每個下一個鏈接的 position。 當您想要隨機位置且不重疊時,根本沒有其他方法。
這是非重疊功能的一個工作示例。 如果您希望您的鏈接甚至不接觸,您應該在if
語句條件中將<
更改為<=
和>
更改為>=
。
var positions = [];
$(".navigationItem").each(function(){
var ctx = $(this);
var dim = {
width: ctx.outerWidth(),
height: ctx.outerHeight()
};
var success = false;
// repeat positioning until free space is found
while (!success)
{
dim.left = parseInt(Math.random() * 300);
dim.top = parseInt(Math.random() * 300);
var success = true;
// check overlapping with all previously positioned links
$.each(positions, function(){
if (dim.left < this.left + this.width &&
dim.left + dim.width > this.left &&
dim.top < this.top + this.height &&
dim.top + dim.height > this.top)
{
success = false;
}
});
}
positions.push(dim);
ctx.animate({
left: dim.left,
top: dim.top
}, "slow");
});
您可以將 position 值更改為relative
。
看我的例子: http://jsfiddle.net/NmmX6/2/
我更改了您的循環,使其不依賴於 id:
function moveAll() {
$('.navigationItem').each(function(i,e){
var rdm = Math.random() * 500;
$(e).animate({"left":rdm + "px"}, "slow");
$(e).animate({"top": rdm + "px"}, "slow");
});
}
我對其進行了測試,並沒有發現它實際上重疊的一種情況,但請檢查一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.