Force page zoom at 100% with JS

2019-01-22 07:19发布

问题:

I created a little game in Canvas, but I have a problem. Some users who have the default zoom set to something other than 100% can't see the entire game page.

I have tried using this CSS:

zoom: 100%;

This HTML

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

And this JS:

style="zoom: 75%"

Any ideas how to programatically set the page zoom?

回答1:

You can set zoom property on page load

document.body.style.zoom = 1.0

But, zoom is not a standard property for all browsers, I recommend using transform instead.

var scale = 'scale(1)';
document.body.style.webkitTransform =  scale;    // Chrome, Opera, Safari
 document.body.style.msTransform =   scale;       // IE 9
 document.body.style.transform = scale;     // General

http://jsfiddle.net/5RzJ8/



回答2:

You can reset the code with this:

$("input, textarea").focusout(function(){
    $('meta[name=viewport]').remove();
    $('head').append('<meta name="viewport" content="width=device-width, maximum-scale=1.0, user-scalable=0">');

    $('meta[name=viewport]').remove();
    $('head').append('<meta name="viewport" content="width=device-width, initial-scale=yes">' );
});


回答3:

I think, this is very helpful answer how to detect page zoom level in all modern browsers. Then the answer to your question for IE:

document.body.style.zoom = screen.logicalXDPI / screen.deviceXDPI;


回答4:

The only way I found that works natively is in designing my HTML/CSS with the units "vw" and "vh" (% relative to the viewport) instead of "px". You can use it everywhere you used to put "px" (font-size, width, height, padding, margin, etc...). Very useful for a page designed to be display full screen only (no scroll) or "Kiosk-style". "vw" and "vh" are not affected by browser zoom. See: https://www.w3schools.com/cssref/css_units.asp