Добавление класса на основе глубины прокрутки относительно другого элемента - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь добавить класс на основе глубины прокрутки, но получаю "getBoundingClientRect is not a function" в консоли и не вижу эффекта.

См. Здесь: https://www.regatta.pl/short-femme-highton-seal-grey/?overflow

JS Б / у:

var  leftSection = document.getElementsByClassName('js-detail-product'),
     leftSectionTop = leftSection.getBoundingClientRect().top,
     rightSection = document.getElementsByClassName('js-product-info-main'),
     rightSectionHeight = rightSection.getBoundingClientRect().height;

if(leftSectionTop <= rightSectionHeight) {
      rightSection.className = ('active');
} else if(leftSectionTop >= rightSectionHeight) {
      rightSection.className =  ('inactive');
}

Ответы [ 2 ]

1 голос
/ 13 июля 2020

getElementsByClassName возвращает массив.

Попробуйте следующее:

leftSection = document.getElementsByClassName('js-detail-product')[0],
leftSectionTop = leftSection.getBoundingClientRect().top,

rightSection = document.getElementsByClassName('js-product-info-main')[0],
rightSectionHeight = rightSection.getBoundingClientRect().height;

Или, возможно, для большей безопасности:

document.addEventListener("DOMContentLoaded", function () {

    allLeftSections = document.getElementsByClassName('js-detail-product');
    if(allLeftSections.length > 0) {
        leftSection = allLeftSections[0],
        leftSectionTop = leftSection.getBoundingClientRect().top,
    }

    allRightSection = document.getElementsByClassName('js-product-info-main');
    if(allRightSection.length > 0) {
        rightSection = allRightSection[0],
        rightSectionHeight = rightSection.getBoundingClientRect().height;
    }
});
1 голос
/ 13 июля 2020

Попробуйте следующее:

  document.addEventListener("DOMContentLoaded", () => {
    //insert all your code here
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...