[英]How do I grab the ID of $this using jQuery and 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>
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-
開頭刪除正文中的所有類(請參閱此答案以供參考) id
添加為類(刪除了不必要的“ if”構造) mapk,您$ this與jquery選擇器的響應有關,在您的情況下,它檢索article元素列表,並且您的算法將其威脅為一個。
考慮在代碼內使用foreach
$(function() {
$("article").waypoint(function(direction) { //callback when waypoint is reached, with direction of scroll as a parameter
$(this).each(function(i,val){
var $this = $(val); // 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");
};
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.