[英]JavaScript works for one id but not another?
I have a JavaScript file which essentially draws a line when the user scrolls down the page. 我有一个JavaScript文件,当用户向下滚动页面时,该文件实际上会画一条线。 It draws a line for the first SVG but not for the other (which uses the same class).
它为第一个SVG画了一条线,但没有为其他SVG(使用相同的类)画一条线。 For example, I have the following code block in both
text-repeater.php
and text-block.php
: 例如,在
text-repeater.php
和 text-block.php
中都有以下代码块:
<svg height="100" width="200">
<line class="line__svg" id="line" x1="0" y1="0" x2="0" y2="200" />
</svg>
And here is my parallax.js
file: 这是我的
parallax.js
文件:
var scrollLine = document.getElementById("line");
var length = scrollLine.getTotalLength();
// Start position of drawing
scrollLine.style.strokeDasharray = length;
// Find scroll percentage on scroll
window.addEventListener("scroll", myFunction);
function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var draw = length * scrollpercent;
// Reverse drawing (when scrolling upwards)
scrollLine.style.strokeDashoffset = length - draw;
}
The line draws in text-block.php
but not in text-repeater.php
该行绘制在
text-block.php
但不在text-repeater.php
Ideas why? 想法为什么?
Also, on a related note. 另外,在相关说明中。 How can I get the line to draw longer?
如何获得更长的线条? It's very subtle at the moment.
目前非常微妙。
That's how IDs work. 这就是ID的工作方式。 You only can have one instance of an Id (kind of - there are tricks but you don't want to do that).
您只能拥有一个Id实例(有点-有花招,但您不想这样做)。
Instead use classes... 而是使用类...
<tagName class="line">
...and loop over it: ...然后遍历:
// Selecting all lines
const scrollLineCollection = document.querySelectorAll(".line");
for ( const scrollLine of scrollLineCollection ) {
// do something with scrollLine
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.