javascript 使用 jquery 更改视口元标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25523284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:38:11  来源:igfitidea点击:

change viewport meta tag with jquery

javascriptjqueryhtmlcssmedia-queries

提问by AB.

I was wondering if it is possible to add a meta tag using jquery to an html page before the page loads. The reason why I ask, is because I have a page with no viewport meta tag on and it should have it only when the resolution drops below 700px - <meta name="viewport" content="width=device-width, initial-scale=1"/>

我想知道是否可以在页面加载之前使用 jquery 将元标记添加到 html 页面。我问的原因是因为我有一个没有打开视口元标记的页面,只有当分辨率低于 700 像素时才应该有它 -<meta name="viewport" content="width=device-width, initial-scale=1"/>

The reason being, I have html markup for mobile site (using media queries) & also html markup for desktop version ( I don't have one for tablets). I want to make sure html markup designed for desktop is rendered properly on tablet on page load and also when we change the device orientation.

原因是,我有用于移动网站的 html 标记(使用媒体查询)和用于桌面版本的 html 标记(我没有用于平板电脑的标记)。我想确保为桌面设计的 html 标记在页面加载时以及当我们更改设备方向时在平板电脑上正确呈现。

Thanks in advance!

提前致谢!

回答by Andy Holmes

Using jQuery you can do it like the following:

使用 jQuery,您可以执行以下操作:

if ($(window).width() < 700) {
   $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1"/>');
}

EDIT

编辑

To have the viewport tag by default, then remove it above 699px:

要默认使用视口标签,然后将其删除到 699px 以上:

HTML:

HTML:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>

jQuery:

jQuery:

if ($(window).width() > 699) {
   $('head').remove('<meta name="viewport" content="width=device-width, initial-scale=1"/>');
}

回答by Zak

Try this (you don't need the /at the end of the meta tag anymore):

试试这个(你不再需要/元标记末尾的 ):

if(screen.width < 700) {
    $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1">');
}

回答by Axel

Sure you can as soon as the jQuery library is loaded and the head is registered at the DOM:

当然你可以在加载 jQuery 库并在 DOM 中注册头部后:

if (jQuery('html').outerWidth(true) < 700) {
  jQuery.('head').append('<meta name="viewport" content="width=device-width, initial-scale=1"/>');
}