0

我希望能够设置不同的视口元标记,具体取决于设备是否为 iPad,如果是 iPad,是否用于纵向或横向视图。

正如David Walsh在这篇文章中所描述的,由于 Apple 的 iPad 用户代理字符串,它应该可以使用 JavaScript 实现。

像这样的东西:

if isiPad and max-width=768px -> use viewport meta for portrait
else if isiPad and max-width=1024px -> use some viewport meta for landscape
else (not iPad) -> use default viewport meta for non-iPad devices;
also (some kind of event listener) if ipad's max-width changes from 768 to 1024, or from 1024 to 768 - use corresponding viewport meta. 

有人能熟练地将其翻译成实际的 JavaScript 吗?

非常感谢您的帮助!

4

1 回答 1

1
var isIpad = navigator.userAgent.match(/iPad/) != null;
if (isIpad) {
    var meta = document.createElement("meta");
    meta.setAttribute("viewport", "whatever");
    var head = document.getElementsByTagName("head")[0];
    head.appendChild(meta);
} else {
    // etc..
};

window.onresize = function(event) {
    var width = window.clientWidth; // This works for Android + iOS.
    var meta = document.createElement("meta");
    meta.setAttribute("viewport", "whatever");
    var head = document.getElementsByTagName("head")[0];
    var metas = document.getElementsByTagName("meta");
    for (var i = 0, i < metas.length; i++) {
         if (metas[i].getAttribute("whatever") == "blabla")//removal condition
             head.removeChild(metas[i]);
    };
    head.appendChild(meta);

};
于 2013-05-09T16:12:06.187 回答