代码 HTML包含实现图片点击放大、拖拽和滚动缩放功能的JavaScript代码

2024-11-19 06:09:21 +0800 CST views 542

该文本是一个HTML文档,包含实现图片点击放大、拖拽和滚动缩放功能的JavaScript代码。用户可以点击图片放大查看,使用鼠标滚轮进行缩放,并通过拖动来移动放大的图片。代码中包含了对图片尺寸的计算和调整逻辑,确保图片在不同屏幕尺寸下的适配性。

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
 
<body>
  <div class="imgBox">
    <img style="width: 150px; height: 150px; padding: 10px" src="https://www.chenxutan.com/uploads/2024/10/22/bookmac.webp" class="img-responsive" />
    <img style="width: 150px; height: 150px; padding: 10px" src="https://www.chenxutan.com/uploads/2024/10/22/bookmac.webp" class="img-responsive" />
  </div>
  <div id="outerdiv" style="
        position: fixed;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.7);
        z-index: 2;
        width: 100%;
        height: 100%;
        display: none;
      ">
    <img id="bigimg" src="" />
  </div>
 
  <script>
	/**
	 * 实现图片点击放大、拖拽、滚轴滚动焦点缩放功能,相关参数、函数声明
	 */
    let imgWidth, imgHeight; // 图片点击放大初始尺寸参数
    let maxZoom = 4; //最大缩放倍数
    let minreduce = 0.5; // 最小缩放倍数
    let initScale = 1; //滚动缩放初始倍数,并不是图片点击放大的倍数
    let isPointerdown = false; //鼠标按下的标识
    //记录鼠标按下坐标和按下移动时坐标
    let lastPointermove = {
      x: 0,
      y: 0,
    };
    //移动过程从上一个坐标到下一个坐标之间的差值
    let diff = {
      x: 0,
      y: 0,
    };
    //图片放大后左上角的坐标,主要结合diff参数用于鼠标焦点缩放时图片偏移坐标
    let x = 0;
    let y = 0;
 
    // 记录节点
    const allImg = document.querySelectorAll(".imgBox img");
    const outerdiv = document.querySelector("#outerdiv");
    const image = outerdiv.querySelector("#bigimg");
    window.onload = function () {
      allImg.forEach((item) => {
        item.addEventListener("click", (e) => {
          const that = e.target;
          image.style.transform = "scale(1)";
          //图片放大展示函数调用
          imgShow(that);
          // 监听鼠标滚动事件
          window.addEventListener("wheel", handleStopWheel, {
            passive: false,
          });
          // 拖转事件调用
          imgDrag();
        });
      });
    };
 
    function imgShow(that) {
      let src = that.getAttribute("src");
      image.setAttribute("src", src);
 
      // 设置尺寸和调整比例
      let windowW = document.documentElement.clientWidth;
      let windowH = document.documentElement.clientHeight;
      let realWidth = image.naturalWidth; //获取图片的原始宽度
      let realHeight = image.naturalHeight; //获取图片的原始高度
      let outsideScale = 0.8;
      let belowScale = 1.4;
      let realRatio = realWidth / realHeight;
      let windowRatio = windowW / windowH;
 
      // 说明:下面是我自己的一些判断逻辑,大致意思就是图片的真实尺寸大于屏幕尺寸则使用屏幕尺寸,如果小于屏幕尺寸就使用自己本身的尺寸;并根据大于或者小于的比例对图片的尺寸进一步调整。coder可以根据自己的要求进行修改。
      if (realRatio >= windowRatio) {
        if (realWidth > windowW) {
          imgWidth = windowH * outsideScale;
          imgHeight = (imgWidth / realWidth) * realHeight;
        } else {
          if (realWidth * belowScale < windowW) {
            imgWidth = realWidth * (belowScale - 0.2);
            imgHeight = (imgWidth / realWidth) * realHeight;
          } else {
            imgWidth = realWidth;
            imgHeight = realHeight;
          }
        }
      } else {
        if (realHeight > windowH) {
          imgHeight = windowH * outsideScale;
          imgWidth = (imgHeight / realHeight) * realWidth;
        } else {
          if (realHeight * belowScale < windowW) {
            imgHeight = realHeight * (belowScale - 0.2);
            imgWidth = (imgHeight / realHeight) * realWidth;
          } else {
            imgWidth = realWidth;
            imgHeight = realHeight;
          }
        }
      }
 
      //设置放大图片的尺寸、偏移量并展示
      image.style.width = imgWidth + "px";
      image.style.height = imgHeight + "px";
      x = (windowW - imgWidth) * 0.5;
      y = (windowH - imgHeight) * 0.5;
      image.style.transform = `translate3d(${x}px, ${y}px, 0)`;
      outerdiv.style.display = "block";
 
      // 点击蒙版及外面区域放大图片关闭
      outerdiv.onclick = () => {
        outerdiv.style.display = "none";
        initScale = 1;
        window.removeEventListener("wheel", handleStopWheel);
      };
 
      // 阻止事件冒泡
      image.onclick = (e) => {
        e.stopPropagation();
      };
    }
 
    function handleStopWheel(e) {
      let itemSizeChange = 1.1; //每一次滚动放大的倍数
      if (e.target.id == "bigimg") {
        // 说明:e.dataY如果大于0则表示鼠标向下滚动,反之则向上滚动,这里设计为向上滚动为缩小,向下滚动为放大
        if (e.deltaY < 0) {
          itemSizeChange = 1 / 1.1;
        }
        let _initScale = initScale * itemSizeChange;
 
        // 说明:在超过或低于临界值时,虽然让initScale等于maxZoom或minreduce,但是在后续的判断中放大图片的最终倍数并没有达到maxZoom或minreduce,而是跳过。
        if (_initScale > maxZoom) {
          initScale = maxZoom;
        } else if (_initScale < minreduce) {
          initScale = minreduce;
        } else {
          initScale = _initScale;
        }
        const origin = {
          x: (itemSizeChange - 1) * imgWidth * 0.5,
          y: (itemSizeChange - 1) * imgHeight * 0.5,
        };
        // 计算偏移量
        if (_initScale < maxZoom && _initScale > minreduce) {
          x -= (itemSizeChange - 1) * (e.clientX - x) - origin.x;
          y -= (itemSizeChange - 1) * (e.clientY - y) - origin.y;
          e.target.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${initScale})`;
        }
      }
 
      // 阻止默认事件
      e.preventDefault();
    }
 
    function imgDrag() {
      // 绑定 鼠标按下事件
      image.addEventListener("pointerdown", pointerdown);
      // 绑定 鼠标移动事件
      image.addEventListener("pointermove", pointermove);
      image.addEventListener("pointerup", function (e) {
        if (isPointerdown) {
          isPointerdown = false;
        }
      });
      image.addEventListener("pointercancel", function (e) {
        if (isPointerdown) {
          isPointerdown = false;
        }
      });
    }
 
    function pointerdown(e) {
      isPointerdown = true;
      console.log(e.pointerId)
 
      // 说明:Element.setPointerCapture()将特定元素指定为未来指针事件的捕获目标。指针的后续事件将以捕获元素为目标,直到捕获被释放。可以理解为:在窗口不是全屏情况下,我在拖动放大图片时即使鼠标移出可窗口之外,此时事件还是捕获在该放大图片上。
      image.setPointerCapture(e.pointerId);
 
      lastPointermove = {
        x: e.clientX,
        y: e.clientY,
      };
    }
 
    function pointermove(e) {
      if (isPointerdown) {
        const current1 = {
          x: e.clientX,
          y: e.clientY,
        };
        diff.x = current1.x - lastPointermove.x;
        diff.y = current1.y - lastPointermove.y;
        lastPointermove = {
          x: current1.x,
          y: current1.y,
        };
        x += diff.x;
        y += diff.y;
        image.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${initScale})`;
      }
      e.preventDefault();
    }
  </script>
</body>
 
</html>
复制全文 生成海报 前端开发 JavaScript 网页设计

推荐文章

JavaScript数组 splice
2024-11-18 20:46:19 +0800 CST
最全面的 `history` 命令指南
2024-11-18 21:32:45 +0800 CST
Go 开发中的热加载指南
2024-11-18 23:01:27 +0800 CST
Manticore Search:高性能的搜索引擎
2024-11-19 03:43:32 +0800 CST
linux设置开机自启动
2024-11-17 05:09:12 +0800 CST
三种高效获取图标资源的平台
2024-11-18 18:18:19 +0800 CST
JavaScript设计模式:桥接模式
2024-11-18 19:03:40 +0800 CST
API 管理系统售卖系统
2024-11-19 08:54:18 +0800 CST
浅谈CSRF攻击
2024-11-18 09:45:14 +0800 CST
PHP 唯一卡号生成
2024-11-18 21:24:12 +0800 CST
php腾讯云发送短信
2024-11-18 13:50:11 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
联系我们
2024-11-19 02:17:12 +0800 CST
支付轮询打赏系统介绍
2024-11-18 16:40:31 +0800 CST
程序员茄子在线接单