从一个 Waypoints.js 构造函数动态定位多个 HTML 元素

ser*_*ays 3 javascript jquery jquery-waypoints

我一直在使用名为Waypoints.js的优秀 JS 插件来根据用户的视口位置更改 CSS 类。现在我正在尝试动态创建这些航点。

我想出了两种不成功的方法。

鉴于此 HTML:

<div class="emp-question-set fade-up" id="emp-question-set-1"></div>
<div class="emp-question-set fade-up" id="emp-question-set-2"></div>
<div class="emp-question-set fade-up" id="emp-question-set-3"></div>
Run Code Online (Sandbox Code Playgroud)

方法 1:使用for循环和getElementByID

// Number of question areas
var questionCount = $('.emp-question-set').length;

// Setup variables
var waypointName, selector, selectorjQuery;

// Start at 2, leave the first item to load normally
for (var i = 1; i <= questionCount; i++) {
  waypointName = 'questionsRollIn' + i;
  selector = 'emp-question-set-' + i;
  selectorjQuery = '#emp-question-set-' + i;

  waypointName = new Waypoint({
    element: document.getElementById(selector),
    handler: function(direction) {
      if (direction === 'down') {
        $(selectorjQuery).addClass('fade-up-active');
      }
      if (direction === 'up') {
        $(selectorjQuery).removeClass('fade-up-active');
      }
    },
    offset: '70%'
  });
}
Run Code Online (Sandbox Code Playgroud)

方法 2:使用 getElementsByClassName

  questionsRollIn = new Waypoint({
    element: document.getElementsByClassName('emp-question-set'),
    handler: function(direction) {
      if (direction === 'down') {
        $('emp-question-set').addClass('fade-up-active');
      }
      if (direction === 'up') {
        $('emp-question-set').removeClass('fade-up-active');
      }
    },
    offset: '70%'
  });
Run Code Online (Sandbox Code Playgroud)

希望你们中的一位能提供帮助,提前致谢。

Dav*_*itz 5

我认为您的第一种方法的问题在于对 JavaScript 闭包如何工作的错误理解。当来自 Java 或 C# 等语言时,这有时会令人困惑。请注意,您的局部变量对于事件处理程序所在的闭包来说是全局的。最后,在执行事件时,您的局部变量 'selectorJquery' 可能包含意外内容。您可以通过将变量的内容记录到 JavaScript 控制台来验证这一点。

第二种方法可能无法工作,因为您似乎试图绑定一组元素,而 js API 可能只需要一个元素。

你可以这样试试(未经测试)

// just in case we need the waypoints later on
var waypoints = [];

$('.emp-question-set').each(function(index, value) {

    var that = $(value)

    var waypoint = new Waypoint({
        element: value,
        handler: function(direction) {
            if (direction === 'down') {
                that.addClass('fade-up-active');
            }
            if (direction === 'up') {
                that.removeClass('fade-up-active');
            }
            },
            offset: '70%'
    });
    waypoints.push(waypoint);
});
Run Code Online (Sandbox Code Playgroud)

这有点类似于您的第一种方法。这里的想法是用类迭代所有元素,.emp-question-set并为每个元素创建一个航点对象。重要的是我们确保每个处理程序都生活在他自己的闭包中。因此不会发生可变碰撞。