我想将logoSocialHeight()函数的结果调用到$(‘header.main’).css(‘top’,logoSocialHeight()).hover(
它只应在窗口加载或视口大小调整时触发.我尝试在1600px以下的屏幕分辨率下调用所有内容.但是logoSocialHeight()仅在我第一次加载超过1600px分辨率的网页时才有效,而不是将其缩小到1600px以下,它将被触发,否则不会.
是否有一个jquery方式的window.addEventListeners,就像$(window).on(‘load resize’?
function logoSocialHeight() {
var logoHeight = $('header.main .logo').outerHeight(true);
var socialHeight = $('header.main .social-links').outerHeight(true);
var sum = -Math.abs(logoHeight + socialHeight - 10);
console.log(sum);
return sum;
};
window.addEventListener('load', logoSocialHeight, false);
window.addEventListener('resize', logoSocialHeight, false);
function bindNavUp() {
var lastScrollTop = 0, delta = 5;
$(window).on('scroll', function() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta) {
return;
};
if (st > lastScrollTop) {
// downscroll code
$('header.main').css('top',logoSocialHeight()).hover(
function() {
$('header.main').css('top','0');
}
);
}
else {
// upscroll code
$('header.main').css('top','0');
};
lastScrollTop = st;
});
};
function unbindNavUp() {
$(window).unbind('scroll');
};
function handleNavUp() {
if ($(window).width() < 1600) {
bindNavUp();
}
else {
unbindNavUp();
};
};
$(document).ready(function() {
var timer;
$(window).on('load resize scroll', function() {
clearTimeout(timer);
timer = setTimeout(function() {
handleNavUp();
}, 100);
});
handleNavUp();
});
更新:
工作简化的代码:
function logoSocialHeight() {
var logoHeight = $('header.main .logo').outerHeight(true);
var socialHeight = $('header.main .social-links').outerHeight(true);
var sum = -Math.abs(logoHeight + socialHeight - 10);
//console.log(sum);
return sum;
};
function bindNavUp() {
var lastScrollTop = 0, delta = 5;
$(window).on('scroll', function() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta) {
return;
};
if (st > lastScrollTop) {
// downscroll code
$('header.main').css('top',logoSocialHeight()).hover(
function() {
$('header.main').css('top','0');
}
);
}
else {
// upscroll code
$('header.main').css('top','0');
};
lastScrollTop = st;
});
};
function unbindNavUp() {
$(window).unbind('scroll');
};
$(window).on('load resize', function() {
if ($(this).width() < 1600) {
bindNavUp();
}
else {
unbindNavUp();
};
});
最佳答案 我会评论,但遗憾的是< 50代表所以我不被允许并被迫写在这里.我不确定这是否会对你有所帮助,因为我对JQuery不太熟悉,但是当你在普通的JavaScript中添加事件监听器时,你不能在注册时使用括号“()”.您只需要命名该功能.
$('header.main').css('top',logoSocialHeight).hover(