更改鼠标滚轮时,Javascript Element.ClassName始终返回true

时间:2018-09-28 17:58:59

标签: javascript jquery

我有一个滚轮功能,可在您上下滚动时更改div的类。

它实际上在所有现代浏览器中都运行良好,事实是,即使我有验证可以阻止这种情况的发生,它也在尝试每次执行时都更改类。

该函数询问div是否已经激活了该类,则它不应更改,但是如果您查看控制台,尽管进行了验证,它仍尝试每次执行该操作。

我不知道为什么className方法总是返回true

我使用了jQuery的hasClass函数,并且具有相同的行为。

非常感谢您的帮助。

JAVASCRIPT代码:

var sections = ['one', 'two', 'three', 'four', 'five'];

function changeSection(section) {
  for (var x = 0; x < sections.length; x++) {
    $('#bg-main').removeClass('bg-' + sections[x]);
    if (sections[x] === section) {
      if (document.getElementById('bg-main').className != ('bg-' + section)) {
        $('#bg-main').addClass('bg-' + section);
        console.log("Active: " + section);
      } else {
        console.log("Inactive: " + sections[x]);
      }
    }
  }
}
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"
if (document.attachEvent)
  document.attachEvent("on" + mousewheelevt, displaywheel)
else if (document.addEventListener)
  document.addEventListener(mousewheelevt, displaywheel, false)
var position = 0;

function displaywheel(e) {
  var evt = window.event || e
  var delta = evt.detail ? evt.detail : evt.wheelDelta
  if (delta < 0) {
    position = (mousewheelevt == 'DOMMouseScroll') ? position - 1 : position + 1;
  } else {
    position = (mousewheelevt == 'DOMMouseScroll') ? position + 1 : position - 1;
  }

  if (position < 0) position = 0;
  if (position > 100) position = 100;

  // Change sections on Scroll
  if (position >= 0 && position <= 19) {
    changeSection('one');
  } else if (position >= 20 && position <= 39) {
    changeSection('two');
  } else if (position >= 40 && position <= 59) {
    changeSection('three');
  }
  if (position >= 60 && position <= 79) {
    changeSection('four');
  } else if (position >= 80 && position <= 100) {
    changeSection('five');
  }
}

CSS代码:

#bg-main {
  width: 100%;
  height: 300px;
}

.bg-one {
  background-color: blue;
}

.bg-two {
  background-color: red;
}

.bg-three {
  background-color: green;
}

.bg-four {
  background-color: yellow;
}

.bg-five {
  background-color: purple;
}

HTML代码:

<div id="bg-main" class="bg-one">SCROLL TO SEE THE CHANGE OF BACKGROUND</div>

工作方式: https://jsfiddle.net/9vpuj582/

1 个答案:

答案 0 :(得分:1)

在检查元素是否具有传递给函数的类之前,要删除该类(因此您的if语句永远不会为假)。

在您的changeSection函数中放置以下代码行是您的问题:

$('#bg-main').removeClass('bg-'+sections[x]);

您可以简化当前的功能。首先检查元素是否已经具有所需的类。然后,如果没有,则从元素中删除所有类(而不是遍历它们并检查每个类),然后添加新类。例如:

const bg = $('#bg-main');

function changeSection(section) {
  if (!bg.hasClass('bg-' + section)) {
    bg.removeClass();
    bg.addClass('bg-' + section);
  }
}