我的网站 - 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>
2 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
这是一个同时显示移动视图和桌面视图的问题,然后禁用哪个“视图”不正确。由于您的javascript在页面创建后加载,它将显示两个视图,直到javascript加载并禁用一个。
您可以通过从开始“禁用”它们来解决这个问题 - 将样式属性添加style="display:none"
到“not-desktop”和“container”。这样他们两个都将被禁用,直到javascript可以启用一个。
编辑:在看了李金尧的回答后,我发现有一种更快的方法可以做到这一点 - 使用CSS媒体标签来检查元素的宽度,只有符合要求时才显示它。然后,使用java脚本检查userAgent和其他任何内容,并相应地更改显示的元素。
慕沐林林
TA贡献2016条经验 获得超9个赞
因为您的脚本是在加载HTML后执行的。因此,在浏览器读取您的脚本之前,移动设备会保持可见状态。
我建议你使用CSS媒体查询来解决这个问题而不是使用脚本。
另一种方式是设定#not-desktop
的display
,以none
你的CSS。然后当脚本执行时,如果它在移动设备上显示,您的代码将显示它。但这种方法并不灵活。
添加回答
举报
0/150
提交
取消