在函数中添加多个 ID

Add multiple ids in a function

本文关键字:ID 添加 函数      更新时间:2023-09-26

我正在尝试使此代码适用于多个id,但我无法使其工作。我已经尝试过querySelectorAll,但没有成功。我也读过这篇文章,但没有一个选项对我有用谁能帮我?

这是代码:

<script>
         function Scroller(options) {
           this.svg = options.el;
           //Animation will end when the end is at which point of othe page. .9 is at about 90% down the page/
           // .1 is 10% from the top of the page. Default is middle of the page.
           this.animationBounds = {};
           this.animationBounds.top = options.startPoint || .5;
           this.animationBounds.bottom = options.endPoint || .5;
           this.animationBounds.containerBounds = this.svg.getBoundingClientRect();
           this.start = this.getPagePosition('top');
           this.end = this.getPagePosition('bottom');
           this.svgLength = this.svg.getTotalLength();
           this.svg.style.strokeDasharray = this.svgLength;
           this.animateLine();
           window.addEventListener('scroll', this.animateLine.bind(this));
         }
         Scroller.prototype.getPagePosition = function (position) {
           //These positions are all relative to the current window. So they top of the page will be negative and thus need to be
           //subtracted to get a positive number
           var distanceFromPageTop = document.body.getBoundingClientRect().top;
           var divPosition = this.animationBounds.containerBounds[position];
           var startPointInCurrentWindow = window.innerHeight * this.animationBounds[position];
           return divPosition - distanceFromPageTop - startPointInCurrentWindow;
         };
         Scroller.prototype.animateLine = function () {
           this.currentVisiblePosition = window.pageYOffset;
           if (this.currentVisiblePosition < this.start) {
             this.svg.style.strokeDashoffset = this.svgLength;
           }
           if (this.currentVisiblePosition > this.end) {
             this.svg.style.strokeDashoffset = '0px';
           }
           if (this.currentVisiblePosition > this.start && this.currentVisiblePosition < this.end) {
             this.svg.style.strokeDashoffset = this.distanceRemaining() * this.pixelsPerVerticalScroll() + 'px';
           }
         };
         Scroller.prototype.distanceRemaining = function () {
           return this.end - this.currentVisiblePosition;
         };
         Scroller.prototype.pixelsPerVerticalScroll = function () {
           this.verticalDistance = this.end - this.start;
           return this.svgLength / this.verticalDistance;
         };
         new Scroller({
            'el': **document.getElementById('line')**,
             'startPoint': .8,
             'endPoint': .5
         });
      </script>

遍历与选择器匹配的所有元素。

var lines = document.querySelectorAll("#line, #line1, #line2");
for (var i = 0; i < lines.length; i++) {
    new Scroller({
        el: lines[i],
        startPoint: .8,
        endPoint: .5
    });
}