100

I have an AJAX app built for mobile Safari browser that needs to display different types of content.

For some content, I need user-scalable=1 and for other ones, I need user-scalable=0.

Is there a way to modify the value of the content attribute without refreshing the page?

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
4

3 回答 3

152

我意识到这有点老了,但是,是的,它可以做到。一些 javascript 可以帮助您入门:

viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');

只需更改您需要的部分,Mobile Safari 就会尊重新设置。

更新:

如果源中还没有 meta viewport 标签,可以直接附加如下内容:

var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);

或者,如果您使用的是 jQuery:

$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');
于 2010-11-04T08:27:47.797 回答
8

在你的<head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

在你的 javascript 中的某个地方

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

...但是祝您好运,为您的设备调整它,摆弄几个小时...我仍然不在那里!

资源

于 2011-05-05T18:58:50.557 回答
5

这已经得到了大部分的回答,但我会扩展......

步骤1

我的目标是在某些时候启用缩放,并在其他时候禁用它。

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

第2步

视口标签将更新,但捏缩放仍处于活动状态!我必须找到一种方法来获取页面以获取更改...

这是一个 hack 解决方案,但切换 body 的不透明度就可以了。我敢肯定还有其他方法可以做到这一点,但这对我有用。

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

第 3 步

我的问题在这一点上基本解决了,但还没有完全解决。我需要知道页面的当前缩放级别,以便我可以调整一些元素的大小以适应页面(想想地图标记)。

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

我希望这对某人有所帮助。在找到解决方案之前,我花了几个小时敲打鼠标。

于 2016-04-27T15:43:31.873 回答