繁体   English   中英

JavaScript适用于一个ID,但不适用于另一个ID?

[英]JavaScript works for one id but not another?

我有一个JavaScript文件,当用户向下滚动页面时,该文件实际上会画一条线。 它为第一个SVG画了一条线,但没有为其他SVG(使用相同的类)画一条线。 例如,在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>

这是我的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;
}

该行绘制在text-block.php但不在text-repeater.php

想法为什么?

另外,在相关说明中。 如何获得更长的线条? 目前非常微妙。

这就是ID的工作方式。 您只能拥有一个Id实例(有点-有花招,但您不想这样做)。

而是使用类...

<tagName class="line">

...然后遍历:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM