当窗口中显示.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 */
});
});
答案 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(); });