javascript - 我的网站在显示正确内容之前,会在桌面上显示移动视图几分之一秒。我怎样才能防止它这样做呢?
问题描述
我的网站 - 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>
解决方案
因为您的脚本是在 HTML 加载后执行的。因此,在浏览器读取您的脚本之前,移动设备保持可见。
我建议您使用CSS 媒体查询来解决这个问题,而不是使用脚本。这是一个很好的答案,演示了如何使用media query
目标桌面和移动设备。这个答案可以解决你的问题。
另一种方法是在您#not-desktop
的CSS中设置display
为。none
然后当脚本执行时,如果它在移动设备上显示,您的代码将显示它。但这种方法不灵活。
推荐阅读
- postgresql - 使用 tls 将应用程序连接到 postgresql 集群
- javascript - Django Rest Framework + Serializers + Vue.js,重置密码功能
- node.js - 如何在nodejs中伪造ECONNRESET错误
- javascript - 修改搜索过滤器 // 不同部分的不同命令
- angular - 角度服务变量更新值未反映在组件中
- reactjs - 当浏览器样式与 nextjs 中带有情感样式组件的服务器不同时,样式不适用于第一个客户端渲染(也不是之后)
- jmeter - 尝试在 JMeter 中打开 jmx 文件时出错
- powershell - 如何在 Powershell 约束模式下关闭 excel ComObject
- javascript - 从 three.js 中的文件创建自定义几何图形
- python - 如何在python中比较两个不同编码的字符串?