当 div 底部可见时,我有一个侧边栏变为位置:固定(遵循此 tutorial )。 我的问题是,如果屏幕尺寸大于或等于1025px,我只需要JS才能工作。
我知道我需要类似于 if($(window).width() > 1025)
的东西,但我不知道它需要在哪里。我不太擅长 JS,因此我们将不胜感激。
JS
$(function () {
if ($('.leftsidebar').offset()!=null) {
var top = $('.leftsidebar').offset().top - parseFloat($('.leftsidebar').css('margin-top').replace(/auto/, 0));
var height = $('.leftsidebar').height();
var winHeight = $(window).height();
var footerTop = $('#footer').offset().top - parseFloat($('#footer').css('margin-top').replace(/auto/, 0));
var gap = 100;
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y+winHeight >= top+ height+gap && y+winHeight<=footerTop) {
// if so, ad the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top',winHeight-height-gap +'px');
}
else if (y+winHeight>footerTop) {
// if so, add the fixed class
$('.leftsidebar').addClass('leftsidebarfixed').css('top',footerTop-height-y-gap+'px');
}
else
{
// otherwise remove it
$('.leftsidebar').removeClass('leftsidebarfixed').css('top','315px');
}
});
}
}
最佳答案
这应该有效:
var flag = false;
// This will keep on checking for window size while you are scrolling.
$(window).on("scroll", function() {
if (flag){
// Do whatever you want here
alert("hey");
}
});
$(window).on("resize", function() {
if ($(window).width() >= 1025){
flag = true;
} else {
flag = false;
}
})
关于javascript - 屏幕尺寸大于1024px才执行JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429055/