search
HomeWeb Front-endJS TutorialHow to disable zooming in javascript

How to disable zooming in javascript

Jun 26, 2021 am 10:19 AM
javascript

javascript实现禁止缩放的方法:1、设置对应浏览器的启动参数来禁止用户缩放页面;2、设置meta来禁止用户缩放页面;3、通过js监听来禁止用户缩放页面;4、禁用“ontouchmove”事件;5、通过多点触摸手势库实现。

How to disable zooming in javascript

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript怎么实现禁止缩放?

javascript浏览器禁止用户放大缩小的五种方法

方案一:设置对应浏览器的启动参数来禁止用户缩放页面

这种方案在自建平台上,自选的指定浏览器上效果是可以的,但是不推荐,比如chrome主要通过设置* { touch-acion : none }来实现禁用缩放的方法,具体方案可自行搜索,我也没有进行相关测试。

touch-acion的参数意义如下:

auto:默认值。浏览器允许一些手势(touch)操作在设置了此属性的元素上,例如:对视口(viewport)平移、缩放等操作。

none:禁止触发默认的手势操作。

pan-x:可以在父级元素(the nearest ancestor)内进行水平移动的手势操作。

pan-y:可以在父级元素内进行垂直移动的手势操作。

manipulation:允许手势水平/垂直平移或持续的缩放。任何auto属性支持的额外操作都不支持。

注:touch-action只支持具有CSS width和height属性的元素。这个限制的目的是帮助浏览器优化低延时的手势操作。对于默认不支持此属性的元素,如这种内联元素,可以给它设置display:block这样的CSS属性来支持width和height。未来W3C规范会将此API扩展到支持所有元素。

方案二:设置meta来禁止用户缩放页面

这是搜索后经常出现的方案,但是现在,这个标签在新的浏览器(比如在ios10+)中已经失效,换言之,对于老版本的浏览器可能有效。

在Android的自带浏览器中(例如华为,魅族,小米)第一次手动缩放时,会提示–再次操作可强制缩放网页—;再次缩放也可以缩放;

这一现象意味着meta标签的失效。在Android的chrome中不可以用户缩放(表现正常)

直接上代码(在.html文件中的

之间添加如下语句):
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" name="viewport" />

方案三:通过js监听来禁止用户缩放页面

直接上代码:

window.onload=function(){
  document.addEventListener(&#39;touchstart&#39;,function (event) { 
      if(event.touches.length>=2){ 
        event.preventDefault(); 
      } 
  }) 
  
  document.addEventListener(&#39;touchmove&#39;,function (event) { 
      if(event.touches.length>=2){ 
        event.preventDefault(); 
      } 
  }) 
  
  document.addEventListener(&#39;touchend&#39;,function (event) { 
      if(event.touches.length>=2){ 
        event.preventDefault(); 
      } 
  }) 
}

其中的event.touches.length是获取当天有几个点击事件同时发生,简单而言,就是有几个手指同时点击了屏幕,以为一般缩放操作都是两个手指以上进行的,所以这里应该满足的条件为event.touches.length>=2。不足之处就是禁用了所有的多点触控的操作。

【推荐:javascript高级教程

方案四:禁用“ontouchmove”事件

因为缩放屏幕必然跟随着双指的ontouchmove事件,我们在标签内加入禁用该事件的函数event.preventDefault()即可,这招非常暴力,意味着全局无法使用使用滑动、拖动等动作,只接受点击动作。

代码如下——

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ontouchmove="event.preventDefault();">
  <head> 
    /****some code***/
  </head>
  <body>
    /****some code***/
  </body>
</html>

其中的event.preventDefault()函数将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作)。例如,如果 type 属性是 “submit”,在事件传播的任意阶段可以调用任意的事件句柄,通过调用该方法,可以阻止提交表单。注意,如果 Event 对象的 cancelable 属性是 fasle,那么就没有默认动作,或者不能阻止默认动作。无论哪种情况,调用该方法都没有作用。

写到这里,忽然想到,是否只禁用某个

区块的ontouchmove事件,比如:
<div ontouchmove="event.preventDefault();"></div>

但这种区块禁用的方式我还没有测试,你可以说我比较懒了,自己去测试吧~~~~

然而还没有得瑟一个月,我就有了这个需求,补充如下,直接上实现代码:

var singleTouchFlag; //多指触控标识符
$("#songList").on("touchstart", function (e) {  //引用了jquery库,我所要多指禁止的区域id为“songList”
    // 判断默认行为是否可以被禁用
    console.log("touchstart Entered!!!");
    if (e.cancelable) {
        // 判断默认行为是否已经被禁用
        if (!e.defaultPrevented) {
            e.preventDefault();
        }
    }
    if (1 == parseInt(e.originalEvent.touches.length)) {
        singleTouchFlag = true;
        // do something
    } else {
        singleTouchFlag = false;
    }
});
$("#songList").on("touchmove", function (e) {
    // 判断默认行为是否可以被禁用
    if (e.cancelable) {
        // 判断默认行为是否已经被禁用
        if (!e.defaultPrevented) {
            e.preventDefault();
        }
    }
    if (singleTouchFlag) {
        //do something
    }
});
$("#songList").on("touchend", function (e) {
    // 判断默认行为是否可以被禁用
    console.log("touchend Entered!!!");
    if (e.cancelable) {
        // 判断默认行为是否已经被禁用
        if (!e.defaultPrevented) {
            e.preventDefault();
        }
    }
    if (singleTouchFlag) {
        //do something
        
    }
});

方案五:借助于**多点触摸手势库“hammer.js ”**解决

hammer.js 是一个多点触摸手势库,能够为网页加入Tap、Double Tap、Swipe、Hold、Pinch、Drag等多点触摸事件,免去自己监听底层touchstart、touchmove、touchend事件并且写一大堆判断逻辑的痛苦。

hammer.js 不但支持触摸屏设备的浏览器,在桌面浏览器上,也能将鼠标的点击当做触摸,方便开发人员在桌面浏览器上调试。(JS仔在自己的随手背项目里面也用了hammer.js,真心好用)

直接上代码(在.html文件中的

之间添加如下语句):
<script src = "http://eightmedia.github.com/hammer.js/hammer.js" > </script>
    <script>
        window.onload = function () {
            var hammerMusicBlock = new Hammer(document.getElementById("musicBlock"));
            hammerMusicBlock.ontransformstart = function (ev) { ev.preventDefault(); }; // double fingers touchstart
            hammerMusicBlock.ontransform = function (ev) { ev.preventDefault(); }; // double fingers touchmove
            hammerMusicBlock.ontransformend = function (ev) { ev.preventDefault(); }; // double fingers touchend
        }
    </script>

hammer.js 其他的使用方式简介,直接看代码:

<script src = "http://eightmedia.github.com/hammer.js/hammer.js" > </script>
 
// 先要对监听的DOM进行一些初始化
var hammer = new Hammer ( document . getElementById ( "container" ) ) ;
 
// 然后加入相应的回调函数即可
hammer . ondragstart = function ( ev ) { } ;    // 开始拖动
hammer . ondrag = function ( ev ) { } ; // 拖动中
hammer . ondragend = function ( ev ) { } ; // 拖动结束
hammer . onswipe = function ( ev ) { } ; // 滑动
 
hammer . ontap = function ( ev ) { } ; // 单击
hammer . ondoubletap = function ( ev ) { } ; //双击
hammer . onhold = function ( ev ) { } ; // 长按
 
hammer . ontransformstart = function ( ev ) { } ; // 双指收张开始
hammer . ontransform = function ( ev ) { } ; // 双指收张中
hammer . ontransformend = function ( ev ) { } ; // 双指收张结束
 
hammer . onrelease = function ( ev ) { } ; // 手指离开屏幕
hammer.js 还支持jQuery插件的形式调用:
<script src = "http://eightmedia.github.com/hammer.js/jquery.hammer.js" > </script>
 
$ ( "#element" )
   . hammer ( {
         // 对DOM进行一些初始化,这里可以加入一些参数
   } )
   . bind ( "tap" , function ( ev ) {
         console . log ( ev ) ;
   } ) ;

暂时总结这五种方案,如果有其他更好的方案,请添加到评论区,谢谢。

The above is the detailed content of How to disable zooming in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),