我有一个jQuery函数,如果页面向下滚动超过X像素,则会添加一个新的菜单区域。都好。如果页面刷新超过像素值,则不会触发该功能。我已经尝试将一个额外的事件添加(绑定)到函数处理程序,但没有快乐。我有所期望的效果,但已经使用了额外的代码:
$(window).load(function()
{
var num = 130; //number of pixels before modifying styles
console.log($(window).scrollTop());
// i have tried load, ready. what can I do???
$(window).bind('load scroll', function()
{
if ($(window).scrollTop() > num)
{
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(0);
$('.now_page_overlay').fadeIn(500).css("display","block").css("visibility","visible");
}
else
{
$('.now_page').removeClass('fixed');
$('.now_page_overlay').fadeOut(100).css("display","none").css("visibility","hidden");
$('.now_page_res').fadeIn(500);
//$('#cart_container').fadeIn(500);
}
});
// EXTRA CODE HERE.... FFS there must be a way to bind the function above to page load...
{
if ($(window).scrollTop() > num)
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(100);
$('.now_page_overlay').fadeIn(500).css("display","block").css("visibility","visible");
}
});
如果没有额外的代码,我可以采取哪些措施来实现这一目标?
答案 0 :(得分:1)
它已经在window.onload中,所以只需触发滚动事件:
$(window).on('load', function () {
var num = 130;
$(window).on('scroll', function () {
if ($(window).scrollTop() > num) {
$('.now_page').addClass('fixed');
$('.now_page_res').fadeOut(0);
$('.now_page_overlay').fadeIn(500).css("display", "block").css("visibility", "visible");
} else {
$('.now_page').removeClass('fixed');
$('.now_page_overlay').fadeOut(100).css("display", "none").css("visibility", "hidden");
$('.now_page_res').fadeIn(500);
}
}).trigger('scroll'); // triggers the above function on window.onload
});
答案 1 :(得分:1)
手动触发窗口上的滚动事件:
$(function () {
var num = 130,
$nowPage = $('.now_page'),
$nowPageOverlay = $('.now_page_overlay'),
$nowPageRes = $('.now_page_res');
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$nowPage.addClass('fixed');
$nowPageRes.fadeOut(0);
$nowPageOverlay.fadeIn(500).css("display", "block").css("visibility", "visible");
} else {
$nowPage.removeClass('fixed');
$nowPageOverlay.fadeOut(100).css("display", "none").css("visibility", "hidden");
$nowPageRes.fadeIn(500);
}
});
$(window).trigger('scroll');
});