双指缩放网页

手势缩放网页,用于手机浏览器,仅在via、X浏览器测试过

目前为 2024-09-06 提交的版本,查看 最新版本

// ==UserScript==
// @name         双指缩放网页
// @namespace    https://greasyfork.org/
// @version      0.1
// @description  手势缩放网页,用于手机浏览器,仅在via、X浏览器测试过
// @author       You
// @license MIT
// @run-at       document-end
// @match        *://*/*
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

if(!document.querySelector('meta[name=viewport]')){
let e = document.createElement("meta");e.setAttribute("name", "viewport");e.setAttribute("content", "width=device-width,initial-scale=1,minimum-scale=0.1,maximum-scale=1,user-scalable=no");document.head.appendChild(e);
}

/*若同时使用强制缩放相关的脚本,放大网页会左右滚动,需重置*/
const setViewport=()=>{document.querySelector('meta[name=viewport]').setAttribute('content','width=device-width,minimum-scale=0.1,maximum-scale=1,user-scalable=no');}

//隐藏水平滚动条
document.body.scrollWidth<=window.screen.availWidth&&GM_addStyle("body{overflow-x:hidden;}");setViewport();

//网页宽度大于768,默认缩放0.5
document.body.scrollWidth>768&&(document.body.style.zoom=0.5);

// 定义一个变量来存储初始的触摸点位置和缩放级别
let initialDistance = 0;
let initialScale = 1;

// 定义一个函数来处理触摸开始事件
function handleTouchStart(event) {
  // 确保触摸点的数量为2
  if (event.touches.length === 2) {
    // 计算两个触摸点之间的距离
    initialDistance = Math.hypot(event.touches[0].pageX - event.touches[1].pageX, event.touches[0].pageY - event.touches[1].pageY);
    // 存储初始的缩放级别
    initialScale = document.body.style.zoom || 1;
  }
}

// 定义一个函数来处理触摸移动事件
function handleTouchMove(event) {
  // 确保触摸点的数量为2
  if (event.touches.length === 2) {
	setViewport();
    // 阻止默认事件,例如页面的滚动
    event.preventDefault();
    // 计算新的触摸点距离
    let currentDistance = Math.hypot(event.touches[0].pageX - event.touches[1].pageX, event.touches[0].pageY - event.touches[1].pageY);
    // 计算缩放比例的变化
    let scale = Math.max(Math.min(parseFloat((currentDistance / initialDistance) * initialScale),2),0.3);
    // 应用新的缩放级别到页面
    document.body.style.zoom = scale;
  }
}

// 为触摸事件添加监听器
document.addEventListener('touchstart', handleTouchStart);
document.addEventListener('touchmove', handleTouchMove);
})();