我正在尝试获取航点元素的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>
Java脚本
$(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的方法,但是语法不正确。
最佳答案
您正在使用错误的Waypoint回调函数。
引用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