页面重定向不适用于移动设备

Page Redirect Not Working for mobile device

本文关键字:移动 适用于 不适用 重定向      更新时间:2023-09-26

我有以下代码,当移动设备访问网页时不会重定向。我哪里错了?

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    var bodyclass = $('body').is('.index');
    if ((screen.width <= 800) && (bodyclass = true)) {
      window.location = "m/index.html";
    }
  </script>
  <title>screen stest</title>
</head>
<body class="index">
  <div class="style">
    <h1>index try10000</h1>
  </div>
</body>
</html>

有几件事,首先你确定你的设备是<= 800px宽度吗?其次,您的脚本正在头部加载并阻止加载剩余的 DOM 结构。由于您的代码依赖于正在加载的 DOM,因此您需要将脚本的执行推迟到加载 DOM 之后。将代码包装在 DOM 就绪函数中(使用 jQuery 的示例)。

$(function() {
    var bodyclass = $('body').is('.index');
    if ((screen.width <= 800) && (bodyclass = true)) {
        window.location = "m/index.html";
    }
});

或者更好的是,只需将脚本移动到正文的最后一个元素即可。那么就不需要 DOM 就绪包装器了。