簡體   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