我有一些绝对定位的元素,它们具有不同的
我想做的就是通过将它们向右移动并调整宽度以适应
但是,我在将'left'位置应用于相撞元素时遇到了问题。
我使用https://sourceforge.net/projects/jquerycollision/来检测碰撞。
以下是最终图片的效果图:
position.top
和height
,这些元素是从数据库生成的。我想做的就是通过将它们向右移动并调整宽度以适应
<body>
容器来避免它们相互碰撞。但是,我在将'left'位置应用于相撞元素时遇到了问题。
我使用https://sourceforge.net/projects/jquerycollision/来检测碰撞。
以下是最终图片的效果图:
$('div').each(function() {
var name = $(this).text();
var hits = $(this).collision('div').not(this); // Find colliding elements
console.log(name + ' collides with: ' + hits.length + ' others');
if (hits.length > 0) {
var widthAll = 100 / (hits.length + 1);
// Shift colliding elements to the right with equal width
$(hits).add(this).each(function(i) {
var name = $(this).text();
$(this).css({ 'left': widthAll * i + '%', 'width': widthAll + '%' });
});
}
});
div {
position: absolute;
width: 10em;
font-size: 0.75em;
color: white;
}
.blue {
top: 0;
height: 80%;
background-color: blue;
}
.red {
top: 15%;
height: 5%;
background-color: red;
}
.yellow {
top: 17%;
height: 10%;
background-color: yellow;
color: black;
}
.green {
top: 30%;
height: 5%;
background-color: green;
}
.magenta {
top: 36%;
height: 3%;
background-color: magenta;
}
.cyan {
top: 50%;
height: 5%;
background-color: cyan;
color: black;
}
.brown {
top: 81%;
height: 5%;
background-color: brown;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://rawgit.com/dsbaars/jquery-collision/master/js/jquery-collision.min.js"></script>
<div class='blue'>blue</div>
<div class='red'>red</div>
<div class='yellow'>yellow</div>
<div class='green'>green</div>
<div class='magenta'>magenta</div>
<div class='cyan'>cyan</div>
<div class='brown'>brown</div>
outerWidth
替换width
(这样你就可以随意调整div
的填充而不会出现问题)。 - Alex G