如何用js和CSS在两点之间画一条线
P粉714844743
P粉714844743 2023-09-12 11:41:32
[CSS3讨论组]

这是一个简单的 HTML 页面,包含 2 个点和一条连接这些点的线,使用 jQuery 添加。

结果是线没有连接点,但由于某种原因使线产生了一定的偏移。

function drawLine(){

    const line_ = $("
", { 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;
}
  
  

直线和 2 个点具有 position:absolute;,因此 topleft 相对于容器。 p>

margin 也将所有 3 个设置为零

线顶部设置为 point1 顶部,但线位于 point1 之上。

这是为什么?

P粉714844743
P粉714844743

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号