2016-01-14 48 views
0

我有一个jQuery脚本,应该让一个div有固定的位置,一旦用户进入页面的正确位置。更多的是,脚本添加新的html元素到使用wrapAll()的DOM。 问题是,每当用户滚动到正确的位置时,都会添加一组新的html元素,而在else语句中,unwrap()不起作用。jQuery执行if语句只有一次,并展开元素

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' 
     }); 
    } 
}); 
}); 

任何想法?

Demo here

+0

您可以发布演示? –

+0

作为一个方面说明:由于ID在文档上下文中必须是唯一的,所以不需要使用'wrapAll()','wrap()'就足够了 –

+0

更新了演示的问题,谢谢。 –

回答

0

试试这个检查

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>'); 
} 
+0

首先'navbar'是一类,其次是如何解决OP的问题? –

+0

它会检查任何元素是否已经包装 –

+0

雅,这是一个好点!但我想应该用于展开元素,而不是(或两者) –