jQuery 只执行一次 if 语句并解包元素
jQuery execute if statement only once and unwrap elements
我有一个jQuery脚本,一旦用户进入页面的正确位置,它应该使div具有固定的位置。不仅如此,该脚本还使用 wrapAll() 向 DOM 添加新的 html 元素。问题是每次用户滚动到正确的位置时,都会添加一组新的 html 元素,并且在 else 语句中 unwrap() 不起作用。
jQuery(document).ready(function () {
// This function will be executed when the user scrolls the page.
jQuery(window).scroll (function(e) {
// Get the position of the location where the scroller starts.
var scroller_anchor = jQuery(".get-started").offset().top;
// Check if the user has scrolled and the current position is after the scroller start location and if its not already fixed at the top
if (jQuery(this).scrollTop() >= scroller_anchor && jQuery('.get-a-quote').css('position') != 'fixed' )
{ // Change the CSS of the scroller to hilight it and fix it at the top of the screen.
jQuery('.get-a-quote').css({
'position': 'fixed',
'top': '0px'
});
jQuery('#stiky-btn').wrapAll('<nav class="navbar navbar-default navbar-fixed-top"><div class="container"><div id="navbar" class="navbar-collapse collapse"><ul class="nav navbar-nav navbar-right"></ul></div></div></nav>');
// Changing the height of the scroller anchor to that of scroller so that there is no change in the overall height of the page.
jQuery('.get-started').css('height', '50px');
}
else if (jQuery(this).scrollTop() < scroller_anchor && jQuery('.get-a-quote').css('position') != 'relative')
{ // If the user has scrolled back to the location above the scroller anchor place it back into the content.
// Change the height of the scroller anchor to 0 and now we will be adding the scroller back to the content.
jQuery('.get-started').css('height', '0px');
jQuery("#stiky-btn").unwrap();
// Change the CSS and put it back to its original position.
jQuery('.get-a-quote').css({
'position': 'relative'
});
}
});
});
有什么想法吗?
在这里演示
试试这个检查
if($("#stiky-btn").parent('.navbar').length == 0){
jQuery('#stiky-btn').wrapAll('<nav class="navbar navbar-default navbar-fixed-top"><div class="container"><div id="navbar" class="navbar-collapse collapse"><ul class="nav navbar-nav navbar-right"></ul></div></div></nav>');
}
相关文章:
- 仅悬停一个元素(活动元素)
- Javascript 解包元素的一部分
- 更改包含其他元素的元素的文本
- jQuery或JavaScript获取靠近其他元素的元素
- 使用jquery计算包含另一个带边距元素的元素的高度
- 获取/更改包含其他元素的元素的类.JavaScript/JQuery
- 从页面中删除除数组中包含的元素及其父元素/子元素之外的所有元素
- 更改元素父元素的背景颜色时停止在
上闪烁鼠标悬停?jQuery/JS. - 给定一个 bySelector 我如何获取此元素子元素的选择器
- 如何获取离子对话框中动态加载的元素的元素高度
- 独立于原始元素复制元素
- AngularJs 指令元素子元素给出空
- Jquery 更改克隆元素子元素的 ID 不起作用
- 隐藏所有没有类匹配所选元素的元素
- 如何从 iframe 元素更改元素属性
- jQuery,如何在HTML中正确查找父元素的元素类型
- jQuery 只执行一次 if 语句并解包元素
- 将数据传递给跨包元素
- 在点击AngularJS指令中的跨包元素时调用一个函数
- AngularJS: ng-controller on指令对指令内的跨包元素不起作用