首页 > 解决方案 > 我的网站在显示正确内容之前,会在桌面上显示移动视图几分之一秒。我怎样才能防止它这样做呢?

问题描述

我的网站 - https://wilfredopersonal.herokuapp.com/# - 显示了一些用于移动视图的特定内容。问题是在加载桌面内容时,此内容也会显示在桌面中。我怎样才能防止它这样做?

<script>
  function isMobile() {
    if (navigator.userAgent.match(/Mobi/)) {
      return true;
    }

    if ("screen" in window && window.screen.width < 1366) {
      return true;
    }

    var connection =
      navigator.connection ||
      navigator.mozConnection ||
      navigator.webkitConnection;
    if (connection && connection.type === "cellular") {
      return true;
    }

    return false;
  }
</script>


<script>
  if (!isMobile()) {
    document.getElementById("not-desktop").style.display = "none";
    document.getElementById("container").style.display = "unset";
  } else {
    document.getElementById("not-desktop").style.display = "unset";
    document.getElementById("container").style.display = "none";
  }
</script>

标签: javascriptreactjs

解决方案


因为您的脚本是在 HTML 加载后执行的。因此,在浏览器读取您的脚本之前,移动设备保持可见。

我建议您使用CSS 媒体查询来解决这个问题,而不是使用脚本。这是一个很好的答案,演示了如何使用media query目标桌面和移动设备。这个答案可以解决你的问题。

另一种方法是在您#not-desktop的CSS中设置display为。none然后当脚本执行时,如果它在移动设备上显示,您的代码将显示它。但这种方法不灵活。


推荐阅读