我编写了一个函数,如果您在设备( $header
)上向下滚动,它可以修复我的顶栏( < 992
),效果很好。当我调整大小时,我使用函数 fixedTopCheck()
再次删除 .fixed
类(在 else 语句中)。这也很好用。但当我滚动时,它突然出现在类的顶部 .fixed
再次。所以这部分被忽略了if ($(window).width() < 992)
(这只发生在调整大小时,如果我用高于 992px 的窗口刷新,它就可以正常工作)。
这种调整大小是否会扰乱 $(window).width()
的识别? ? (当我控制台记录它时,它显示正确的宽度尺寸)。
我的代码:
$(function()
{
var $header = $('header.top');
var $input = $header.find('input[type=search]');
var $search = $header.find('div.search');
var $container = $('main#content');
var $searchBtn = $search.find('button.icon-search');
var $closeBtn = $search.find('span.icon-cross');
$closeBtn.css('display', 'none');
function fixedTopCheck()
{
if ($(window).width() < 992)
{
$(window).on('scroll', function()
{
if ($(window).scrollTop() > 75)
{
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
// Turn top into fixed menu
$header.addClass('fixed');
$container.addClass('fixed');
// Hide search bar and make it smaller
$input.css('display', 'none');
// Prevent search button to search
$searchBtn.on('click', function(e) {
e.preventDefault();
});
// Open search bar when clicking button
$(document).on('click','.icon-search',function()
{
$searchBtn.unbind('click');
$input.css('display', 'inline-block');
$searchBtn.css('display', 'none');
$closeBtn.css('display', 'inline-block');
$input.focus();
});
// Close search bar when clicking button
$(document).on('click','.icon-cross',function()
{
$searchBtn.on('click', function(e)
{
e.preventDefault();
});
$input.css('display', 'none');
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
});
}
else
{
// Reverse fixed menu
$header.removeClass('fixed');
$container.removeClass("fixed");
$input.css('display', 'inline-block');
// Return search function
$searchBtn.unbind('click');
// Reset search form when going top and search form is still opened
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
}
});
}
else
{
console.log("hello");
// Remove fixed top
if($header.hasClass("fixed"))
{
$header.removeClass("fixed");
}
if($container.hasClass("fixed"))
{
$container.removeClass("fixed");
}
$searchBtn.css('display', 'inline-block');
$closeBtn.css('display', 'none');
}
}
fixedTopCheck();
// if window is resized check again
$( window ).resize(function() {
fixedTopCheck();
});
});
最佳答案
您的代码遵循很多不良做法。
不要将事件监听器嵌套在彼此内部。这将导致每次容器事件触发时在同一组件上设置一个事件监听器(每次调整大小也非常繁重)。
不要使用绑定(bind)和取消绑定(bind),而是检查每个事件内的宽度并根据该宽度执行操作。
在您的情况下替换绑定(bind)和取消绑定(bind)的另一个解决方案是保留默认按钮事件,但禁用该按钮,以便无法单击它而不是取消绑定(bind)。
这将回答您的问题:
- 在调整大小内添加事件不会使它们仅在 if 语句中的该大小上起作用,您必须将事件放在调整大小事件之外,并在滚动和大小上发生该事件时进行检查。
关于javascript - Jquery 在调整大小时忽略 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38521850/