我正在使用关于内嵌 SVG 的 this 视频教程作为参考。我试图复制使 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”,但这些都不起作用。有谁知道这里可能有什么问题?