我想沿着一个特定的路径移动一个箭头,我知道我必须应用CSS translate来移动箭头,但我有一个问题。我知道我必须应用CSS translate来移动箭头,但我有一个问题。
箭头需要向下移动,然后向左移动,然后向上移动,直到它从开始的地方到达同一个水平平原,但在其初始位置的左边。
我可以把它向下移动,这是第一步。但如果我使用三种翻译方法,它就会直接把它带到最后的位置,而不遵循路径。我试着把这三种翻译方法和它们的转换放到不同的函数中,并在上一步结束时调用每个函数,但结果是一样的。
这是HTML。
<div>
<img src="img/arwTest.png" alt="Click to rotate" id="arrow">
<img src="img/moveTest_2.png" alt="demonstration" id="demo">
<p>Click anywhere to move the arrow along the path.</p>
</div>
这是CSS
#demo, #arrow {
display: block;
margin: 0 auto;
}
#demo {
height: 300px;
}
#arrow {
height: 40px;
position: absolute;
left: 50%;
}
p {
text-align: center;
padding: 20px;
}
这里是JavaScript
const arrow = document.getElementById("arrow");
arrow.style.transform = `rotate(90deg)`;
addEventListener('click', () => {
arrow.style.transform = `translate(0px,200px)`;
arrow.style.transition = `2s`;
})
我相信您正在寻找的是 @关键帧 css语句,以及 动画 css属性。
@keyframes motion {
0.000% { left: 30%; top: 70%; }
33.33% { left: 70%; top: 70%; }
66.66% { left: 50%; top: 30%; }
100.0% { left: 30%; top: 70%; }
}
html, body {
position: absolute;
width: 100%; height: 100%;
left: 0; top: 0;
margin: 0; padding: 0;
}
.point {
position: absolute;
width: 20px; height: 20px;
margin-left: -10px; margin-top: -10px;
border-radius: 100%;
background-color: #500000;
animation: motion 2000ms infinite linear;
}
<div class="point"></div>
一个新的CSS属性可以帮助你解决这个问题。
它是offset-path。
请看代码段中如何使用它来实现你所要求的移动。
悬停容器来激活它
另外,请注意,在Stack overflow中,要求你发布一个代码的例子。即使它不工作!
#container {
width: 400px;
height: 150px;
border: dotted 5px black;
margin: 30px;
}
#motion-demo {
width: 40px;
height: 40px;
background: cyan;
offset-path: path('M400 0 v 150 h -400 v -150');
offset-distance: 0%;
transition: offset-distance 2s;
}
#container:hover #motion-demo {
offset-distance: 100%;
}
<div id="container">
<div id="motion-demo"></div>
</div>