【问题标题】:JavaScript when brower resize reload to different page浏览器调整大小时的 JavaScript 重新加载到不同的页面
【发布时间】:2020-10-19 18:44:48
【问题描述】:

我最近创建了一个网站以获得一点乐趣。我有两台显示器,一台 15 英寸和一台 24 英寸。我在使用 15 英寸显示器时网站出现问题,在着陆页上看起来很奇怪.我想我会做一些javascript,所以当它检测到15英寸以下的东西时,它会重新加载页面并转到移动版本。它可以工作,但有人可以帮我在调整大小时自动重新加载到移动页面吗?我会很高兴.请不要判断,因为我对 JS 一无所知,但这是我想出的。如果有人能提供帮助,我会很感激。

if (screen.width <= 1440) { reload(); document.location = "mobileindex.html"; }

【问题讨论】:

  • 这段代码基本没问题,除了一些细节。一方面,它需要在windowonresize 事件的事件处理函数中,并且您应该使用window.innerWidth 而不是screen.width。最后,调用reload(); 将刷新页面,就像您按了 F5 一样。你会想要删除它。 window.onresize = () => window.innerWidth < 1440 && document.location = "mobileindex.html";

标签: javascript html css resize


【解决方案1】:

因此,您要查找的内容称为 EventListener,这将在某些事件(例如调整浏览器窗口大小)时触发。
此外,您可能想查看https://www.w3schools.com/jsref/,因为它对于初学者来说是一个非常好的资源。
至于这样做的代码:

window.addEventListener("resize", function(){
    var width  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if (width <= 1440) window.location.replace("example.html"); 
});

[编辑]

因此,以英寸为单位计算屏幕尺寸有点复杂,标准方法是使用像素,但如果您设置使用 In here is a resource,您可以使用。
因此,通常需要为您的代码选择 3 个断点、3 个屏幕宽度。
流行的分辨率是 360x640 (mobile)、768x1024 (tablet) 和 1366x768 (desktop)。
所以你最终会得到这样的结果:

window.addEventListener("resize", function(){
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var currentPage = window.location.origin; 
    if (width <= 420 && !currentPage.includes("mobile")) window.location.replace("mobile.example.html"); 
    else if(width >= 1280 && !currentPage.includes("desktop")) window.location.replace("desktop.example.html"); 
    else if(!currentPage.includes("tablet")) window.location.replace("tablet.example.html"); 
});

currentPage.includes("tablet") 用于在您进入正确页面后停止重定向循环。

【讨论】:

  • 非常感谢@HiltonSiegert。当它检测到 24 英寸时,我怎样才能让它回到正常索引?
  • 抱歉回复慢。我已经更新了我的答案以提供更多信息。
【解决方案2】:

你不能重新加载到不同的页面吗?因为你说要切换到手机版...如果我的理解是正确的,手机版和桌面版应该有相同的内容,只是CSS样式不同。如果是这样,您甚至不必使用 javascript。

//css file

//this is just an example
.body{
    margin: 10px;
    font-size: 100px;
}

//when the page is resized to 15inch or below, the bottom code will run
@media(max-width: 1440px //15inch){
    .body{
        margin: 0px;
        font-size: 50px;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 2020-03-27
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多