Javascript 防止缩放跨浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27116221/
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
Prevent zoom cross-browser
提问by Basj
For a map-like tool, I would like to disable the browser zooming feature. (I know that this is generally a bad idea, but for some specific website, it is needed).
对于类似地图的工具,我想禁用浏览器缩放功能。(我知道这通常是一个坏主意,但对于某些特定网站,它是必需的)。
I did it successfully by listening the keyboard shortcut CTRL+/ CTRL-and adding e.preventDefault(), etc.
But this doesn't prevent from changing the zoom from the browser's Zoom menu.
我通过听键盘快捷键CTRL+/CTRL-和添加e.preventDefault()等成功做到了。
但这并不能阻止从浏览器的缩放菜单更改缩放。
I tried:
我试过:
with CSS:
zoom: reset;It works for Chrome (see this page for a working example) but it doesn't work at all on Firefox.in various questions/answers, I also found
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">but this seems to work for mobile only.
使用 CSS:
zoom: reset;它适用于 Chrome(有关工作示例,请参阅此页面)但在 Firefox 上根本不起作用。在各种问题/答案中,我还发现
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">但这似乎仅适用于移动设备。
How to prevent zooming cross-browser ?
如何防止跨浏览器缩放?
回答by Vijay Dhanvai
You can disable zoom in browser by Ctrl+ or Ctrl- or Using Ctrl Key + Mouse wheel Up or down by this code.
您可以通过 Ctrl+ 或 Ctrl- 或使用 Ctrl 键 + 鼠标滚轮向上或向下通过此代码禁用浏览器放大。
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109' || event.which == '187' || event.which == '189' ) ) {
event.preventDefault();
}
// 107 Num Key +
// 109 Num Key -
// 173 Min Key hyphen/underscor Hey
// 61 Plus key +/= key
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey == true) {
event.preventDefault();
}
});
Check a demo here http://jsfiddle.net/VijayDhanvai/4m3z3knd/
回答by hon2a
I haven't really found an "authoritative" answer, meaning a clear statement from browser developers. However, all answers to similar questions I've found (like this oneor that one) suggest the same thing - the browser's zoom feature exists for the benefit of the users and some browsers (like Firefox) simply don't allow you, as a website creator, to take this option away from them.
我还没有真正找到“权威”的答案,这意味着浏览器开发人员的明确声明。然而,我发现的类似问题的所有答案(比如这个或那个)都表明了同样的事情——浏览器的缩放功能是为了用户的利益而存在的,而一些浏览器(比如 Firefox)根本不允许你,因为网站创建者,从他们那里拿走这个选项。
This documentationmight shed some light into why allowing authors to disable zoom might be a good idea on mobile devices, but not on desktops.
本文档可能会阐明为什么允许作者禁用缩放在移动设备上可能是一个好主意,但在台式机上则不然。
In short, you might need to prevent mobile devices from initially auto-zooming your website, if you know their calculated auto-zoom will be inappropriate. On desktops, there is no auto-zoom, so when users come to your website, they see it exactly as it was meant to be seen.If they then decide they need to zoom the page, there's no good reason to let you prevent them from doing so.
简而言之,您可能需要阻止移动设备最初自动缩放您的网站,如果您知道它们计算出的自动缩放是不合适的。在台式机上,没有自动缩放功能,因此当用户访问您的网站时,他们看到的内容完全符合预期。如果他们随后决定需要缩放页面,则没有充分的理由让您阻止他们这样做。
As for the solutions you've listed:
至于您列出的解决方案:
zoomis a non-standard property not supported by Firefox, and<meta name="viewport">is concerned only with devices on which layout viewportand visual viewportare not the same thing, i.e. mobile devices.
zoom是Firefox 不支持的非标准属性,并且<meta name="viewport">只用在哪些设备有关布局视和视觉视口是不一样的东西,即移动设备。
回答by thunder
I think what you can do is, listen to browser zoom event(ctrl + "+") and then check for window.devicePixelRatio.
我认为您可以做的是,收听浏览器缩放事件(ctrl + "+"),然后检查 window.devicePixelRatio。
Then accordingly, apply HTML5 scale transformation on the body element to scale down by the same ratio. So, basically you cannot prevent the functionality but you can apply negative effect with the same magnitude.
然后相应地,对 body 元素应用 HTML5 缩放转换以按相同的比例缩小。因此,基本上您无法阻止该功能,但您可以应用相同量级的负面影响。
POC Code:
验证码:
<body style="position: absolute;margin: 0px;">
<div style="width: 300px; height: 200px; border: 1px solid black;">
Something is written here
</div>
<script>
var keyIncrease = [17, 61];
var keyDecrease = [17, 173];
var keyDefault = [17, 48];
var listenMultiKeypress = function(keys, callback){
var keyOn = [];
for(var i=0; i<keys.length; i++){
keyOn[i] = false;
}
addEventListener('keydown', function(e){
var keyCode = e.which;
console.log(keyCode);
var idx = keys.indexOf(keyCode);
if(idx!=-1){
keyOn[idx] = true;
}
console.log(keyOn);
for(var i=0; i<keyOn.length; i++){
if(!keyOn[i]){
return;
}
}
setTimeout(callback, 100);
});
addEventListener('keyup', function(e){
var keyCode = e.which;
var idx = keys.indexOf(keyCode);
if(idx!=-1){
keyOn[idx] = false;
}
console.log(keyOn);
});
};
var previousScale = 1;
var previousDevicePixelRatio;
var neutralizeZoom = function(){
//alert('caught');
var scale = 1/window.devicePixelRatio;
document.body.style.transform = 'scale('+(1/previousScale)+')';
document.body.style.transform = 'scale('+scale+')';
var widthDiff = parseInt(getComputedStyle(window.document.body).width)*(scale-1);
var heightDiff = parseInt(getComputedStyle(window.document.body).height)*(scale-1);
document.body.style.left = widthDiff/2 + 'px';
document.body.style.top = heightDiff/2 + 'px';
previousScale = scale;
};
listenMultiKeypress(keyIncrease, neutralizeZoom);
listenMultiKeypress(keyDecrease, neutralizeZoom);
listenMultiKeypress(keyDefault, neutralizeZoom);
neutralizeZoom();
</script>
</body>
</html>
回答by David
So, as has been mentioned, that really isn't possible. However, there are some ways you can still be smart about it.
所以,正如已经提到的,这真的是不可能的。但是,您仍然可以通过一些方法来了解它。
Three of the five major browsers all allow you to see the zoom level of the browser, furthermore, should the browser be zoomed a window.onresizeevent is fired.
五个主要浏览器中的三个都允许您查看浏览器的缩放级别,此外,如果浏览器被缩放,则会触发window.onresize事件。
IE: event.view.devicePixelRatio OR window.view.devicePixelRatio
Chrome: event.currentTarget.devicePixelRatio OR window.devicePixelRatio
Firefox: event.originalTarget.devicePixelRatio OR window.devicePixelRatio
Safari: /* Not possible */
Opera: /* Not possible */
I think the stuff after OR works based on something I noticed as I was messing around. The first ones I know work in at least the latest version of each one. Note that Safari and Opera both have the devicePixelRatio, however both never change. It's always just 1.
我认为 OR 之后的东西是基于我在胡闹时注意到的东西。我知道的第一个至少在每个版本的最新版本中工作。请注意,Safari 和 Opera 都有devicePixelRatio,但都不会改变。它总是只是1。
The above is your easy way if you don't care thatmuch. If you do, then you could try out the detect-zoomscript, which I came across while looking for solutions to Safari and Opera.
如果您不太在意,以上是您的简单方法。如果您这样做了,那么您可以尝试检测缩放脚本,这是我在寻找 Safari 和 Opera 的解决方案时遇到的。
So what you can now do is get the zoom level, and then offset your zoom to where it doesn't do anything. So if I force my browser to 50% zoom, you just go to 200%. Thus, no change. Of course it will be a bit more complicated, you'll have to store the last browser zoom, the new browser zoom, and do some slightly more complicated math, but based on what you already have, that should be a breeze.
所以你现在可以做的是获得缩放级别,然后将缩放偏移到它不做任何事情的地方。因此,如果我强制浏览器缩放 50%,您只需缩放到 200%。因此,没有变化。当然,它会更复杂一些,您必须存储上次浏览器缩放比例、新浏览器缩放比例,并进行一些稍微复杂的数学运算,但根据您已有的内容,这应该是轻而易举的。
Another idea might be to just listen for a resize event, and calculate based off the new visible size, but that might cause issues if the window is just resized. I think the above is going to be your best option, with perhaps a fallback alertto warn the user not to zoom if necessary.
另一个想法可能是只侦听调整大小事件,并根据新的可见大小进行计算,但如果只是调整窗口大小,这可能会导致问题。我认为以上将是你最好的选择,也许有后备alert警告用户在必要时不要缩放。
回答by Jeremy Levett
Insert the following into your HTML:
将以下内容插入到您的 HTML 中:
For Mobiles: Insert between the '< head>...< /head>' tag.
对于手机:在“< head>...</head>”标签之间插入。
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
For Desktops across-Browsers: Insert just after start '< body>...' tag.
对于跨浏览器的桌面:在开始 '<body>...' 标签之后插入。
<script>
document.body.addEventListener("wheel", e=>{
if(e.ctrlKey)
event.preventDefault();//prevent zoom
});
</script>
回答by Andrii Gordiichuk
I updated code Vijay code:
我更新了代码 Vijay 代码:
$(document).ready(function(){
var keyCodes = [61, 107, 173, 109, 187, 189];
$(document).keydown(function(event) {
if (event.ctrlKey==true && (keyCodes.indexOf(event.which) != -1)) {
alert('disabling zooming');
event.preventDefault();
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey == true) {
alert('disabling zooming');
event.preventDefault();
}
});
});
This solution is cross-platform (OS / Win) for desktop browsers.
此解决方案是针对桌面浏览器的跨平台 (OS/Win)。
回答by B. Colin Tim
It is simple:
很简单:
function load(){
document.body.addEventListener("wheel", zoomShortcut); //add the event
}
function zoomShortcut(e){
if(e.ctrlKey){ //[ctrl] pressed?
event.preventDefault(); //prevent zoom
if(e.deltaY<0){ //scrolling up?
//do something..
return false;
}
if(e.deltaY>0){ //scrolling down?
//do something..
return false;
}
}
}
p {
display: block;
background-color: #eeeeee;
height: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Mousewheel control!</title>
</head>
<body onload="load()">
<p>If your Mouse is in this Box, you can't zoom.</p>
</body>
</html>
回答by Shanu Shaji
$(document).ready(function () {
$(document).keydown(function (event) {
if (event.ctrlKey == true && (event.which == '107' || event.which == '109' || event.which == '187' || event.which == '189'))
{
event.preventDefault();
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey == true) {
event.preventDefault();
}
});
})
回答by rfornal
Have you tried ...
你有没有尝试过 ...
$("body").css({
"-moz-transform":"scale(1)",
"-webkit-transform":"scale(1)",
"-o-transform":"scale(1)",
"-ms-transform":"scale(1)"
});
I've used this type of code to set or re-set the scale.
我已经使用这种类型的代码来设置或重新设置比例。

