当我悬停在一个元素上时,我试图在这个元素周围画一个SVG路径。
我用CSS对动画进行了如下编码:
#circle-1 {
fill-opacity: 0;
fill: transparent;
stroke: #000;
stroke-width: 1;
stroke-dasharray: 163px;
stroke-dashoffset: 163px;
animation-name: circle;
animation-duration: 4000ms;
animation-iteration-count: 1;
animation-play-state: paused;
}
@keyframes circle {
to {
stroke-dashoffset: 0;
}
}效果很好。当我试图在兄弟元素悬停时触发动画时,它就停止工作了,如下所示:
HTML
<h1 id="link-1">#1</h1>
<svg width="57px" height="46px" viewBox="0 0 57 46" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="circle-1">
<path d="M1252.39102,182.674299 C1222.56333,182.674299 1186.23852,210.300373 1230.21581,223.998154 C1278.92632,239.170208 1268.93364,185.408886 1243.06946,182.674299" id="Path-3"></path>
</g>
</svg>CSS
#circle-1 {
fill-opacity: 0;
fill: transparent;
stroke: #000;
stroke-width: 1;
stroke-dasharray: 163px;
stroke-dashoffset: 163px;
animation-name: circle;
animation-duration: 4000ms;
animation-iteration-count: 1;
animation-play-state: paused;
}
#circle-1.active {
animation-play-state: running;
}
@keyframes circle {
to {
stroke-dashoffset: 0;
}
}JS
window.onload = function() {
var circle1 = document.getElementById("circle-1");
var link1 = document.getElementById("link-1");
for (var i = 0; i < circle1.length; i++) {
link1[i].addEventListener('mouseover', function() {
circle1.classList.add('active');
return false;
});
}
};查看这里的代码:https://codepen.io/louden/pen/YLeBXB
我不想使用jQuery。
发布于 2018-05-09 22:52:22
若干问题:
var circle1 = document.getElementById("circle-1");返回路径元素。那么,for (var i = 0; i < circle1.length; i++) {应该在那里做什么呢?使用getElementsByTagName等作为列表..。
路径d属性扩展到svg,因此要扩展svg,首先清除所有过时的widht/height属性。使用viewBox属性和preserveAspectRatio="none"。这样你就可以控制高宽比了。宽度和高度的USe css。
起作用的小提琴:
https://jsfiddle.net/ibowankenobi/40p2fqgc/1/
无限动画:https://jsfiddle.net/ibowankenobi/40p2fqgc/2/
<h1 id="link-1">#1</h1>
<svg viewBox="0 0 2000 2000" preserveAspectRatio="none" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<path id="circle-1" d="M1252,182 C1222,182 1186,210 1230,223 C1278,239 1268,185 1243,182"/>
</svg>这是用于单击处理程序的:
https://jsfiddle.net/ibowankenobi/40p2fqgc/10/
顺便提一句,getElementsByTagName是实时的,所以您不必再调用它了。
这是一个取消鼠标的动画:
https://stackoverflow.com/questions/50262843
复制相似问题