我正在使用这个关于内联 SVG 的视频教程作为参考。我正在尝试复制使 SVG 线看起来从中点向外绘制的效果。视频方法和我的方法之间的唯一区别是,在视频中,SVG 线具有预定义的长度,而我的方法是可变长度。
该方法背后的想法非常简单。您制作一条任意大小的 SVG 线,然后将其 stroke-dasharray 属性设置为 '0, length/2' 并将其 stroke-dashoffset 属性设置为 '-length/2',这样就根本不会绘制该线首先,它的“起点”设置在它的中间点。然后,当相关输入字段被聚焦时,将 dasharray 属性更改为“length, 0”,将 dashoffset 属性更改为 0。这使得破折号等于线的长度。这应该使线看起来从中间点拉入,如果你从一开始就知道线的长度,确实会发生这种情况。但是,当我尝试使用没有预定长度的行来实现这种方法时,情况并非如此。我的线似乎是从线的最开头而不是从中间点开始画的。我很困惑为什么会这样。我正在使用 JavaScript 来计算行的长度。下面是我的代码片段。
function animateLine() {
const input = document.querySelector('.input');
const line = document.querySelector('.focus');
const length = line.getTotalLength();
line.style.strokeDasharray = `0, ${length/2}`;
line.style.strokeDashoffset = `-${length/2}`;
input.addEventListener('focus', function() {
line.style.strokeDasharray = `${length}, 0`;
line.style.strokeDashoffset = `0`;
});
};
animateLine();
/* Input module */
.input {
background: none;
border: none;
width: 100 %;
padding: 0.5em;
padding-left: 0;
color: white;
font-family: inherit;
font-size: 0.85em;
}
.input:focus {
outline: none;
}
.line {
width: 100%;
height: 2px;
padding: 0;
stroke: grey;
}
.focus {
stroke: black;
transition: all 5s;
stroke-dasharray: 0, 10000;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="input" type="text" name="review[body]" placeholder="Leave a review..." required>
<svg xmlns="http://www.w3.org/2000/svg" class="line" viewBox="0 0 40 2" preserveAspectRatio="none">
<path d="M0 1 L40 1"></path>
<path d="M0 1 L40 1" class="focus"></path>
</svg>
</body>
</html>
我尝试使用不同的百分比,并且只使用值“20”作为我的半长,因为我的视口长度为“40”,但这些都不起作用。有谁知道这里可能是什么问题?