javascript - 如何使用 jQuery 和 Waypoints 获取 $this 的 ID

标签 javascript jquery jquery-waypoints

我试图获取路径点元素的 ID,然后在滚动到达该路径点时将该 ID 值作为类添加到正文中。但这似乎不起作用。

HTML

<body class="bg-1">
<div id="content">
    <div class="cover">
        <h2>Title</h2>
        <p class="keep-scrolling">Keep scrolling along</p>
    </div>
    <section class="stats">
        <article id="bg-1">
            /* stuff */
        </article>
        <article id="bg-2">
            /* stuff */
        </article>
        <article id="bg-3">
            /* stuff */
        </article>
        <article id="bg-4">
            /* stuff */
        </article>
    </section>
</div>
</body>

Javascript

$(function() {
  $("article").waypoint(function(direction) {  //callback when waypoint is reached, with direction of scroll as a parameter
    var $this = $(this); // caching the waypoint element

    if($this.attr("id") == "bg-1") {
      $("body").removeClass();
      $("body").addClass('bg-1');
    } else if($this.attr("id") == "bg-2") {
      $("body").removeClass();
      $("body").addClass("bg-2");
    } else if($this.attr("id") == "bg-3") {
      $("body").removeClass();
      $("body").addClass("bg-3");
    } else if($this.attr("id") == "bg-4") {
      $("body").removeClass();
      $("body").addClass("bg-4");
    } else {
      $("body").addClass("bg-1");
    };

  });
});

我有很多方法来获取 ID,但无法获得正确的语法。

最佳答案

您使用的航点回调函数错误。

引用API这应该对你有用:

$(function() {
  $("article").waypoint({
    handler: function(direction) {
      $("body").removeClass(function(index, css) {
        return (css.match(/(^|\s)bg-\S+/g) || []).join(' ');
      });
      //or $("body").removeClass();
      $("body").addClass(this.element.id);
    }
  });
});

我对你的解决方案做了一些调整:

  • 从正文中删除以 bg- 开头的所有类(请参阅 this 答案以供引用)
  • id 添加为类(删除了不必要的“if”构造)
<小时/>

<强> Example

关于javascript - 如何使用 jQuery 和 Waypoints 获取 $this 的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901617/

相关文章:

javascript - Highcharts : How to align pie chart positions to right or left corner of the container

javascript - 如何更改 JavaScript 上的 z 索引?

javascript - CSS 向下滚动动画处理轨迹线

ajax - 在 Ajax 之后重新加载 AddToAny

javascript - 不可分配给类型“IntrinsicAttributes”(React.js 和 TypeScript.js)

javascript - 在 Javascript 中按对象文字中的名称(作为字符串)调用函数

encryption - 使用 RSA 技术在 JavaScript 中加密字符串并在 PHP 中解密

javascript - 获取元素个数最多的对象

javascript - 如何使用 jquery waypoint 切换功能

javascript - 滚动到 div 时显示它