javascript – 最初查找页面宽度,并在调整浏览器大小后检查它
作者:互联网
我有这个代码工作,但它似乎笨重我,有没有办法简化?它的要点是我在页面加载时检查页面宽度,并根据该页面显示或隐藏div(基于浏览器是否更宽或者是否超过480像素).然后,如果用户调整浏览器窗口的大小,我会再次检查宽度并显示/隐藏正确的div.无论如何,这可以用jquery或js简化?
function pageWidth() {
return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;
}
//Show/hide the correct div when the page loads
if (pageWidth() >= 480) {
$(".siteSearchDropdown").css("display", "none");
$(".siteSearchSelect").css("display", "block");
}
if (pageWidth() < 480) {
$(".siteSearchDropdown").css("display", "block");
$(".siteSearchSelect").css("display", "none");
}
// Show/hide the correct dropdown when the browser window is resized
$(window).resize(function() {
if (pageWidth() >= 480) {
$(".siteSearchDropdown").css("display", "none");
$(".siteSearchSelect").css("display", "block");
}
if (pageWidth() < 480) {
$(".siteSearchDropdown").css("display", "block");
$(".siteSearchSelect").css("display", "none");
}
});
解决方法:
而不是两次编写代码,在window.resize事件处理程序中写入一次,然后在window元素上触发resize事件:
$(window).resize(function() {
if (pageWidth() >= 480) {
$(".siteSearchDropdown").css("display", "none");
$(".siteSearchSelect").css("display", "block");
}
if (pageWidth() < 480) {
$(".siteSearchDropdown").css("display", "block");
$(".siteSearchSelect").css("display", "none");
}
}).trigger('resize');
此外,由于当有人调整浏览器大小时,此代码将运行多次,您应该通过缓存选择器来优化代码:
var $siteSearchDrioopdown = $(".siteSearchDropdown"),
$siteSearchSelect = $(".siteSearchSelect");
$(window).resize(function() {
if (pageWidth() >= 480) {
$siteSearchDrioopdown.css("display", "none");
$siteSearchSelect.css("display", "block");
}
if (pageWidth() < 480) {
$siteSearchDrioopdown.css("display", "block");
$siteSearchSelect.css("display", "none");
}
}).trigger('resize');
注意:我提到了在调整浏览器大小时如何多次运行resize事件处理程序代码.要自己测试,只需将此代码添加到页面并观察您的开发人员控制台:
$(window).resize(function (e) {
console.log(e);
});
再次查看代码后,您可以使用if / else语句进一步优化,而不是两次运行pageWidth()函数:
var $siteSearchDrioopdown = $(".siteSearchDropdown"),
$siteSearchSelect = $(".siteSearchSelect");
$(window).resize(function() {
if (pageWidth() >= 480) {
$siteSearchDrioopdown.css("display", "none");
$siteSearchSelect.css("display", "block");
} else {//notice the change in structure so the `pageWidth()` function is only called once
$siteSearchDrioopdown.css("display", "block");
$siteSearchSelect.css("display", "none");
}
}).trigger('resize');
标签:javascript,jquery,window-resize 来源: https://codeday.me/bug/20190723/1514349.html