Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

jquery - Show Different Meta Tag Based on Device

Running into all kinds of meta tag issues today...

I want this meta tag to be displayed on devices that are (max-width: 1024px) and (min-width: 768px)...

<meta name="viewport" content="minimum-scale=1.0, maximum-scale=1.0" />

And this meta tag for devices that are (min-width: 320px) and (max-width: 568px)...

<meta name="viewport" content="maximum-scale=1.0" />

Whats the best solution to display the appropriate meta tag?

Can I use "media="only screen and (device-width: 768px)" for example on a meta tag?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't use the media attribute on meta tags according to Mozilla (although you probably should be able to).

The best option, in my opinion, would probably be client-side Javascript, and assuming you are using jQuery, it should be easy to get a reliable reading of the window width.

You don't need to use media queries at all. jQuery provides a .width() shortcut to get the width of a window (you can do this without jQuery, but jQuery makes your reading more reliable than plain Javascript).

if ($(window).width() >= 768 && $(window).width()) <= 1024)
    $('meta').attr('name', 'viewport').attr('content', 'minimum-scale=1.0, maximum-scale=1.0').appendTo('head')
else if ($(window).width() >= 320 && $(window).width() <= 568)
    $('meta').attr('name', 'viewport').attr('content', 'maximum-scale=1.0').appendTo('head')

But, remember that once the window resizes, these rules won't update unless you have code to do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...