gpt4 book ai didi

javascript - Javascript 的媒体查询方法

转载 作者:行者123 更新时间:2023-11-28 15:36:41 25 4
gpt4 key购买 nike

我正在考虑根据设备类型实现/调用 JS,就像我们如何使用 CSS 媒体查询一样。

<link rel="stylesheet" type="text/css" href="desktop.css" media="all" />
<link rel="stylesheet" type="text/css" href="ipad.css" media="only screen and (device-width:768px)" />

同样我们可以定义一些JS并根据设备(桌面/移动)调用它们

我知道一种明显的方法就是使用 if 语句将 2 分开

if (navigation.userAgent.match(/iPad/) != null)

但我所看到的只是应该在设备中加载/调用正确的 JS,例如对于桌面应该只调用 desktop.js,对于 iPad 应该只调用 iPad.js(类似于 css 媒体查询呈现的方式)

请提出建议。

最佳答案

这应该细化为:

// put this in the end of the page to add JS to body (perfomance optimisation on loading behaviour

var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript'; // you can omit this when using HTML5 Doctype
if (navigation.userAgent.match(/iPad/) != null) {
script.src = 'ipad.js';
} else {
script.src = 'desktop.js';
}
body.appendChild(script);

关于javascript - Javascript 的媒体查询方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7722078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com