如何对线条进行动画处理以跟踪移动的 CSS 元素

How to animate a line to track a moving CSS element?

本文关键字:跟踪 移动 元素 CSS 处理 动画      更新时间:2023-09-26

UPDATE - 我曾要求帮助使用 SVG animate 插件修复我的第一次尝试,现在有一个解决方案(点击此链接),它有效地回答了这个问题。尽管 attr() 正如 Jleagle 指出的那样,也可能导致解决方案

我已经使用 jQuery 制作了一个 css 元素数组,下一阶段是用图形直线跟踪每个元素。线的一端应保持固定,一端应随元素移动。

以为我可以使用 SVG 和适当的 SVG jQuery 插件来完成这一点,但我遇到了很多问题,我想知道我是否应该从不同的方向处理它。

下面是带有三行 SVG 行的动画框的代码,因此您可以看到我正在获取的内容。该网站还有一个JS小提琴

爪哇语

$(function() {
var balloons = [$("#box1"), $("#box2"), $("#box3")];
var lines = [$("#line1"), $("#line2"), $("#line3")];
function act(jqObj, speed, change) {
    jqObj.animate({
        'left' : change
    }, speed).animate({
        'left' : -change
    }, speed, function() {
        act(jqObj, speed, change);
    });
};
for( i = 0; i < balloons.length; i++) {
    var speed = 2000 + Math.random() * 501;
    var change = 10 + Math.random() * 26;
    act(balloons[i], speed, change);
}
}); 

网页/CSS

<html>
<head>
    <title>Proof of Concept Page</title>
    <style type="text/css">
        .html .body {
            position: absolute;
        }
        .box {
            position: absolute;
            width: 100px;
            height: 100px;
            position: absolute;
            background-color: red;
        }
        #box1 {
            margin-left: 300px;
            margin-top: 60px
        }
        #box2 {
            margin-left: 500px;
            margin-top: 20px
        }
        #box3 {
            margin-left: 700px;
            margin-top: 50px
        }
    </style>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="main.js"></script>
</head>
<body>
    <div  class="box" id="box1">
        Proj 1
    </div>
    <div  class="box" id="box2">
        Proj 2
    </div>
    <div  class="box" id="box3">
        Proj 3
    </div>
    <svg id="linePad" xmlns="http://www.w3.org/2000/svg" version="1.1">
        <line id="line1" x1="350" y1="160" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
        <line id="line2" x1="550" y1="120" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
        <line id="line3" x1="750" y1="150" x2="550" y2="500" style="stroke:rgb(255,0,0);stroke-width:2"/>
    </svg>
</body>
</html>

您可以将文本和元素放在同一个标签中,并设置文本位置的样式。
然后,您无需修复两个对象的动画。
希望这没问题。