对于移动端,我们可以直接这样限制:
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0, user-scalable=no">
在PC端上:
1、禁止用户在页面上使用ctrl+鼠标滚轮和ctrl+“+”“-”进行页面缩放:
可以在index.html中增加如下代码:
<script>
document.addEventListener('mousewheel', function (e) {
e = e || window.event;
if ((e.wheelDelta && event.ctrlKey) || e.detail) {
event.preventDefault();
}
}, {
capture: false,
passive: false
});
document.addEventListener('keydown', function (event) {
if ((event.ctrlKey === true || event.metaKey === true)
&& (event.keyCode === 61 || event.keyCode === 107
|| event.keyCode === 173 || event.keyCode === 109
|| event.keyCode === 187 || event.keyCode === 189)) {
event.preventDefault();
}
}, false);
</script>
2、在vue项目中,还原用户的缩放操作(对用户在页面上修改浏览器样式也生效)
在App.vue中(最外层父页面)
mounted () {
this.keepRatio()
window.addEventListener('resize', () => {
this.keepRatio()
});
},
在methods中,加入这样一个方法keepRatio:
methods: {
keepRatio () {
var ratio = 0; // 定义一个缩放比例
var screen = window.screen; // 获取窗口对象
var ua = navigator.userAgent.toLowerCase();
if (window.devicePixelRatio !== undefined) {
ratio = window.devicePixelRatio; // 像素大小的比例
}
else if (~ua.indexOf('msie')) {
if (screen.deviceXDPI && screen.logicalXDPI) {
ratio = screen.deviceXDPI / screen.logicalXDPI;
}
}
else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
ratio = window.outerWidth / window.innerWidth; // 外部比例/内部比例:缩放比例
}
if (ratio) {
ratio = Math.round(ratio * 100);
}
this.ratio = (ratio / 100).toFixed(2);
document.body.style.zoom = 1 / this.ratio; // 窗口视图除以缩放比例:即缩放还原
}
}