“这可能吗?”
是的,但为了保持代码的简单性,您需要使用 不同的 方法:根据用户的屏幕宽度将用户发送到三个不同页面之一,而不是加载新的 div在同一页面中。我将逐步解释如何做到这一点。我们开始:
如何使用 JavaScript 检查用户的屏幕宽度:
if(window.innerWidth <= 620){
// The window width is less or equal to 620px.
}
if(window.innerWidth > 620 && window.innerWidth <= 920){
// The window width is greater than 620px and less or equal to 920px.
}
if(window.innerWidth > 920){
// The window width is greater than 920px.
}
如果您将window.innerWidth 值存储在width 变量中,您还可以稍微简化此代码,如下所示:
var width = window.innerWidth;
然后你可以使用if(width > 620){/* Code here */}来检查窗口宽度是否大于620px。
现在您将创建两个或多个页面,每个页面都有一个修改,然后如果用户的屏幕尺寸为X,则将其发送到另一个页面。为此,您只需在上述ifs 中使用location.href="#"; 并将“#”替换为其他页面URL。
处理页面大小调整:
以上代码是有关如何检查用户窗口宽度的示例,但浏览器将在页面加载时运行此代码,仅一次,但在调整大小时不会运行。要让这段代码在浏览器调整大小时运行,您需要将这些 ifs 包装在一个函数中并使用 EventListener 调用它,这将在调整浏览器大小时对代码说。
最终代码结果:
这是移植到函数的最终代码,在 EventListener 中调用并将用户发送到另一个页面:
function checkWidth(){
var width = window.innerWidth;
if(width <= 620){
location.href = "#"; // The window width is less or equal to 620px.
}
if(width > 620 && width <= 920){
location.href = "#"; // The window width is greater than 620px and less or equal to 920px.
}
if(width > 920){
location.href = "#"; // The window width is greater than 620px.
}
}
window.addEventListener('resize', checkWidth);
checkWidth();
JSFiddle Demo