如何根据屏幕尺寸加载不同的主页

How to Load Different Home Page according to screen size

我想根据屏幕大小加载不同的主页。有人可以帮忙吗?

例如, 对于屏幕尺寸 < 960 像素,我想将默认登录页面显示为 index1.html 和 对于屏幕尺寸 > 960 像素,我想将默认登录页面显示为 index2.html

提前致谢。

你已经标记了这个问题 responsive-design,但你问的是如何做 "adaptive design." 响应式设计将有一个单独的 HTML 页面来适应它的媒体被查看,例如通过使用媒体查询。我不会讨论哪个更好,但如果您对响应式设计感兴趣,我会添加此内容,以便您对 google.

有一些想法

完成您所要求的一种方法是在您的页面上添加一些 JavaScript 检查 window 的宽度并在必要时重定向:

// In index2.html
if (window.innerWidth < 960) {
    window.location = "index1.html";
}

// In index1.html
if (window.innerWidth >= 960) {
    window.location = "index2.html";
}

我试过上面的解决方法。它有效,但页面不断重新加载。通过这种方法解决了重新加载问题,我添加了一个功能,可以帮助在视口大小更改时自动重新加载页面。

// refreshing page automatically when viewport size change  
window.onresize = function(event) {
  document.location.reload(true);
}

var href = window.location.href.split("/")
var html_location = href[href.length-1]

if (window.innerWidth >= 960 && html_location !== "index.html") {
    window.location = "index.html";
}

if (window.innerWidth < 960 && html_location !== "index2.html") {
    window.location = "index2.html";
}

我知道不久前有人问过这个问题并回答了这个问题,但我认为我添加的解决方案比公认的答案更好,因为它不涉及重新加载 并且 可以调整大小.定义两个 CSS 类、.HideOnMobile 和 .ShowOnMobile 并在两个顶级 DIV 元素中使用它们。

然后使用媒体查询将这两个类的显示值设置为non或initial,根据屏幕宽度显示或隐藏每个DIV。

@media (max-width: 575.98px) {
  .HideOnMobile {
    display: none;
  }
  .ShowOnMobile {
    display: initial;
  }
}

@media (min-width: 576px) {
  .HideOnMobile {
    display: initial;
  }
  .ShowOnMobile {
    display: none;
  }
}
<div class="ShowOnMobile">
  MOBILE content
</div>
<div class="HideOnMobile">
  DESKTOP content
</div>