我正在使用一些定义了两个断点的响应式设计:
Mobile > max-width 320px
Tablet portrait > max-width 767px
在桌面上,我有很多动画 + Javascript 的高级功能。在移动设备和平板电脑上,我希望简化和禁用一些 JS +“重建”一些 DOM 元素。
我想知道确定某些断点(就宽度而言)的最有效方法是什么?我在这里思考了很多关于性能的问题。
我知道我可以简单地在调整大小时检查窗口宽度,例如:
$( window ).resize(function() {
if ($(window).width() > 320 && $(window).width() < 400) {
//mobile
}
if ($(window).width() > 401 && $(window).width() < 768) {
//tablet
}
if ($(window).width() > 769) {
//desktop
}
});
但这似乎是一个非常“昂贵”的操作?
也非常欢迎任何可用于此目的的轻量级库的建议!
我经常遇到这个问题,但没有找到完美的解决方案。然而,有一种解决方法似乎不太需要资源。通过在
resize()
函数中使用超时并不断清除它,您可以确保您的代码仅在视口停止调整大小后运行。
var resizeTimer, width;
var mobile = tablet = desktop = false;
$(window).resize(function() {
// clear the timeout
clearTimeout(resizeTimer);
// execute breakpointChange() once the viewport
// has stopped changing in size for 400ms
resizeTimer = setTimeout(breakpointChange(), 400);
});
function breakpointChange() {
// use vanillajs window.innerWidth
// instead of jQuery $(window).width() as suggested by simon
width = window.innerWidth;
if (!mobile && width < 400) {
tablet = desktop = false;
mobile = true;
console.log('is mobile');
}
if (!tablet && width > 401 && width < 768) {
mobile = desktop = false;
tablet = true;
console.log('is tablet');
}
if (!desktop && width > 769) {
mobile = tablet = false;
desktop = true;
console.log('is desktop');
}
}
$(window).resize();
window
对象具有
innerWidth
/ outerWidth
属性,无需 jQuery 调用即可使用。$( window ).resize(function() {
var width = window.innerWidth; // e.g.
if (width > 320 && width < 400) {
//mobile
}
});
因此,您不会遇到任何性能问题,因为这只是对象的属性,没有函数调用/强制。如果您确实需要了解该设备,那么这将是完美的解决方案。
当您在内部操作 DOM 时 - 请按照“The F”的建议寻找超时
window.matchMedia()
:
const mobileQuery = window.matchMedia("(max-width: 320px)");
const tabletQuery = window.matchMedia("(max-width: 767px)");
function handleBreakpoints() {
if (mobileQuery.matches) {
console.log("Mobile breakpoint");
} else if (tabletQuery.matches) {
console.log("Tablet breakpoint");
} else {
console.log("Desktop breakpoint");
}
}
// Execute the function initially to set the initial state
handleBreakpoints();
// Add listeners for changes in the media queries
mobileQuery.addListener(handleBreakpoints);
tabletQuery.addListener(handleBreakpoints);
这种方法避免了在每次调整大小事件时连续检查窗口宽度,这可能会占用大量资源。相反,它侦听媒体查询中的变化,并在到达断点时执行适当的代码。