change viewport meta tag with jquery

2019-08-05 04:55发布

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"/>

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.

Thanks in advance!

3条回答
Rolldiameter
2楼-- · 2019-08-05 05:28

Using jQuery you can do it like the following:

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:

HTML:

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

jQuery:

if ($(window).width() > 699) {
   $('head').remove('<meta name="viewport" content="width=device-width, initial-scale=1"/>');
}
查看更多
来,给爷笑一个
3楼-- · 2019-08-05 05:30

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">');
}
查看更多
贼婆χ
4楼-- · 2019-08-05 05:32

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

if (jQuery('html').outerWidth(true) < 700) {
  jQuery.('head').append('<meta name="viewport" content="width=device-width, initial-scale=1"/>');
}
查看更多
登录 后发表回答