- 使用meta标签。
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
- meta标签iOS Safari无效,实现阻止默认事件。
Safari浏览器中有一组事件:gesturestart、gesturechange、gestureend事件,在多个手指出触摸屏幕时触发,可以通过阻止这些事件的默认行为阻止浏览器缩放。
<script>
window.onload = function() {
var lastTouchEnd = 0;
document.addEventListener('touchstart', function(event) {
if (event.touches.length > 1) {
event.preventDefault();
}
});
document.addEventListener('touchend', function(event) {
var now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
document.addEventListener('gesturestart', function(event) {
event.preventDefault();
});
}
</script>
- 监听覆盖屏幕的元素的touch事件,阻止默认行为。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
#container {
width: 100vw;
height: 100vh;
background-color: #4caf50;
}
</style>
</head>
<body>
<div id="container">ABC</div>
<script>
const container = document.getElementById("container");
container.addEventListener("touchstart", (event) => {
if (event.touches.length > 1) {
event.preventDefault();
}
})
container.addEventListener("touchmove", (event) => {
if (event.touches.length > 1) {
event.preventDefault();
}
})
</script>
</body>
</html>