jQuery仅追加一次 [英] jQuery append only once
本文介绍了jQuery仅追加一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有这个:
jQuery("document").ready(function($){
var nav = $('#nav');
var logo = '<img src="img/logo.png" />';
$(window).scroll(function () {
if ($(this).scrollTop() > 136) {
nav.addClass("nav-f");
nav.append(logo);
} else {
nav.removeClass("nav-f");
nav.remove(logo);
}
});
});
滚动时,我试图固定导航,这是可行的,但我也想在#nav div中添加带有徽标图像的标签,该标签也可以工作,但会附加在每次滚动中,因此在滚动时,我会得到100张徽标图像。
When scrolling I'm trying to make the navigation to be fixed, which works, but I also want to add a tag with the logo image in the #nav div, which also works but it appends on every scroll so when scrolling I get like 100 images of the logo.
如何使它仅附加一次,并且滚动时滚动条不能超过136px?
How can I make it to append only once and when it's not scrolled more than 136px to be removed?
推荐答案
只需使用布尔值,
jQuery("document").ready(function($){
var nav = $('#nav');
var logo = '<img id="lilLogo" src="img/logo.png" />';
var visible = false;
$(window).scroll(function () {
if ($(this).scrollTop() > 136) {
nav.addClass("nav-f");
if(!visible) {
nav.append(logo);
visible = true;
}
} else {
nav.removeClass("nav-f");
if(visible) {
$('#lilLogo').remove();
visible = false;
}
}
});
});
另一种方法是使用 $('#lilLogoID')。is(':visible')
,但是这会搜索img并检查每个事件是否可见(这很慢)
The alternative is to check with $('#lilLogoID').is(':visible')
, however this would then do a search for img and check visible on every event (which would be slow)
这篇关于jQuery仅追加一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文