我试图获取路径点元素的 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/