在窗口中显示另一个div时隐藏元素

时间:2017-11-07 20:32:19

标签: jquery html css

当窗口中显示.hidden#pre-footer div时,我需要将类#footer切换到我的粘性菜单。

我一直在搞乱jquery和scrollTop();,但似乎无法实现。任何帮助将不胜感激

$(document).ready(function() {
    var $window = $(window);
  var tabwrap = $('.tab-wrap');
  var prefooter = $('#pre-footer');
  $window.on('scroll', function() {
    var scrollTop = $window.scrollTop();
    tabwrap.toggleClass('hidden', scrollTop > 300); /* Help! */
    /* .tabwrap should toggle class .hidden when #pre-footer and or #footer is visible in window */
  });
});

到目前为止小提琴:https://jsfiddle.net/gavinfriel/4tcjnoxp/5/

2 个答案:

答案 0 :(得分:3)

所以基本上你想在视口底部与#pre-footer的底部对齐时切换类。因此,当scrollTop值+视口的高度大于pre-footer的顶部+ #pre-footer的高度

$(document).ready(function() {
  var $window = $(window);
  var tabwrap = $('.tab-wrap');
  var prefooter = $('#pre-footer');
  var prefooter_top = prefooter.offset().top;
  var prefooter_height = prefooter.height();
  var prefooter_bottom = prefooter_top + prefooter_height;
  console.log(prefooter_bottom);
  $window.on('scroll', function() {
    var scrollTop = $window.scrollTop();
    var viewport_height = $(window).height();
    var scrollTop_bottom = scrollTop + viewport_height;
    tabwrap.toggleClass('hidden', scrollTop_bottom > prefooter_bottom); 
  });
});

答案 1 :(得分:0)

var tabwrap   = $('.tab-wrap');
var prefooter = $('#pre-footer');

/**
 * @desc Check to see if element is inside the viewport
 */
$.fn.isInViewport = function() {
    var element     = $(this),
        elementHt   = element.outerHeight(),
        elementTop  = element.offset().top,
        elementBot  = elementTop + elementHt,

        viewportTop = $(window).scrollTop(),
        viewportBot = viewportTop + $(window).outerHeight(),

        offset      = 0.35 * elementHt; // pecentage of top and bottom

    return (elementBot - offset) > viewportTop && (elementTop + offset) < viewportBot;
};


function checkOffset()
{
    if( prefooter.isInViewport() )
        tabwrap.addClass('hidden');
    else
        tabwrap.removeClass('hidden');
}

$(window)
.load(function(){ checkOffset(); })
.scroll(function(){ checkOffset(); });