下面是一个简单的HTML页面,其中包含两个点和一条用jQuery添加的连接点的线.
结果是这条线没有连接点,而是出于某种原因放置了具有一定偏移量的线.
function drawLine(){
const line_ = $("<div>", { class: "line" });
const p1 = $("#point1");
var p1T = p1.position().top;
var p1L = p1.css("left");
// set line top equal to point1 top
var lineT = p1T + "px";
line_.css ({
width: length + "px",
transform: `rotate(${angle}rad)`,
top: lineT,
left: p1L
});
p1.parent().append(line_);
}
// Get the elements representing the two points you want to draw a line between
const point1 = document.getElementById('point1');
const point2 = document.getElementById('point2');
// Calculate the coordinates of the two points
const point1Rect = point1.getBoundingClientRect();
const point2Rect = point2.getBoundingClientRect();
// Calculate the length and angle of the line
const length = Math.sqrt((point2Rect.left - point1Rect.left) ** 2 + (point2Rect.top - point1Rect.top) ** 2);
const angle = Math.atan2(point2Rect.top - point1Rect.top, point2Rect.left - point1Rect.left);
drawLine();
#line-container {
position: relative;
border: 1px solid blue;
}
.line {
position: absolute;
height: 2px;
background-color: aqua;
margin: 0px;
}
.point{
position: absolute;
margin: 0px;
}
#point1{
background-color: red;
top: 100px;
left: 100px;
width: 10px;
height: 10px;
}
#point2{
background-color: blue;
top: 200px;
left: 300px;
width: 10px;
height: 10px;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="line-container">
<div id="point1" class="point"></div>
<div id="point2" class="point"></div>
</div>
这条线和两个点都是position: absolute;
,所以top
和left
是相对于容器的.
对于所有3个,margin
也设置为0
线TOP被设置为Point1的顶部,但线位于Point1上方.
为什么会这样呢?