不同技术实现鼠标滚动图片的放大缩小

在这里插入图片描述

摘要:

最近弄PC端的需求时,要求在layui技术下实现鼠标滚动图片的放大缩小的功能!下面来总结一下不同框架剩下这功能!

layui:
看了一下layui文档,其实这有自带的组件的!但是又版本要求的!并且layui的官方文档是不维护的了!记得使用最新的版本!

layui.use(['table', "util"]function () {
    var $ = layui.jquery;
    var util = layui.util;
    
    util.event('zoom', function(obj){
    var oImg = document.getElementById('solo_pic');
    var scale = obj.deltaY > 0 ? 1.1 : 0.9; 
    var width = oImg.width * scale;
    var height = oImg.height * scale;
        
    if (width > 500 || width < 10) return;
       oImg.width = width;
       oImg.height = height;
    });
})

jquery:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
    <script src="../static/js/jquery-1.11.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
    $(function() {
        function zoomImg(o) {
            var zoom = parseInt(o.style.zoom, 10) || 100;
            zoom += event.wheelDelta / 12; //可适合修改
            if (zoom > 0) o.style.zoom = zoom + '%';
        }
        $(document).ready(function() {
            $("img").bind("mousewheel",
                function() {
                    zoomImg(this);
                    return false;
                });
        });
    })
    </script>
</head>
 
<body>
   <center>
        <img src="../static/img/111.jpg" border="1px" />
    </center>
</body>
 
</html>

添加遮罩层:

<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
    <script src="../static/js/jquery-1.11.1.min.js" type="text/javascript" charset="utf-8"></script>
    <style>
        /*************图片预览************/
        #outerdiv {
            position: fixed;
            top: 0;
            left: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 2;
            width: 100%;
            height: 100%;
            display: none;
        }
 
        #innerdiv {
            position: absolute;
        }
 
        #bigimg {
            border: 5px solid #fff;
            cursor: pointer;
        }
 
    </style>
    <script type="text/javascript">
    $(function() {
        function zoomImg(o) {
            var zoom = parseInt(o.style.zoom, 10) || 100;
            zoom += event.wheelDelta / 12; //可适合修改
            if (zoom > 0) o.style.zoom = zoom + '%';
        }
        $(document).ready(function() {
            $("img").bind("mousewheel",
                function() {
                    zoomImg(this);
                    return false;
                });
        });
    })
    </script>
</head>
 
<body>
    <center>
        <img id="img" src="../static/img/111.jpg" border="1px" @click="bigimg()" />
    </center>
    <div id="outerdiv">
        <div id="innerdiv">
            <img id="bigimg" src="" onmousewheel="bigimg(this)" />
        </div>
    </div>
    <script>
    $(`#img`).click(function() {
 
        var _this = $(this); //将当前的img元素作为_this传入函数
        imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
    })
    // 图片缩放
    function bigimg(obj) {
        // alert(parseInt(obj.style.zoom, 10));
        //obj是一个对象,初始时obj并没有zoom属性,所以给zoom赋值为100;
        var zoom = parseInt(obj.style.zoom, 10) || 100;
        //每次滚动鼠标时,改变zoom的大小
        //event.wheelDelta有两个值,120,-120,取值情况取决于滚动鼠标的方向;
        zoom += event.wheelDelta / 12; //每次滚动加减10
        if (zoom > 0)
            obj.style.zoom = zoom + '%'; //更改后的zoom赋值给obj
        return false;
    }
    // 预览图片
    function imgShow(outerdiv, innerdiv, bigimg, _this) {
        var src = _this.attr("src"); //获取当前点击的pimg元素中的src属性
        $(bigimg).attr("src", src); //设置#bigimg元素的src属性
        /*获取当前点击图片的真实大小,并显示弹出层及大图*/
        $("<img />").attr("src", src).load(function() {
            var windowW = $(window).width(); //获取当前窗口宽度
            var windowH = $(window).height(); //获取当前窗口高度
            var realWidth = this.width; //获取图片真实宽度
            var realHeight = this.height; //获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8; //缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            if (realHeight > windowH * scale) { //判断图片高度
                imgHeight = windowH * scale; //如大于窗口高度,图片高度进行缩放
                imgWidth = imgHeight / realHeight * realWidth; //等比例缩放宽度
                if (imgWidth > windowW * scale) { //如宽度扔大于窗口宽度
                    imgWidth = windowW * scale; //再对宽度进行缩放
                }
            } else if (realWidth > windowW * scale) { //如图片高度合适,判断图片宽度
                imgWidth = windowW * scale; //如大于窗口宽度,图片宽度进行缩放
                imgHeight = imgWidth / realWidth * realHeight; //等比例缩放高度
            } else { //如果图片真实高度和宽度都符合要求,高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width", imgWidth); //以最终的宽度对图片缩放
            var w = (windowW - imgWidth) / 2; //计算图片与窗口左边距
            var h = (windowH - imgHeight) / 2; //计算图片与窗口上边距
            $(innerdiv).css({ "top": h, "left": w }); //设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast"); //淡入显示#outerdiv及.pimg
        });
        $(outerdiv).click(function() { //再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }
    </script>
</body>
 
</html>

为每个包含图片div元素附加了一个滚轮事件监听器,当用户在这些元素上滚动滚轮时,调用zoomImage函数进行放大/缩小操作。
zoomImage函数内部,通过$(this).find('img')选择器找到了当前元素内img元素,接下来从滚轮事件中获取了用户的滚动方向,然后计算出当前图片的放大/缩小后的宽度和高度,并将其重新赋值给了图片元素。 注意在这个代码中我们同时监听了mousewheelDOMMouseScroll`这两种不同浏览器的滚轮事件,以保证代码能够在不同的浏览器中正常运行。

$(document).ready(function() {
  function zoomImage(event) {
    event.preventDefault();
    var image = $(this).find('img');
    var delta = event.originalEvent.deltaY || event.originalEvent.detail || event.originalEvent.wheelDelta;
    var zoom = delta > 0 ? -0.2 : 0.2;
    var newWidth = image.width() + (image.width() * zoom);
    var newHeight = image.height() + (image.height() * zoom);
    image.width(newWidth).height(newHeight);
  }
  $('div.image-container').on('mousewheel DOMMouseScroll', zoomImage);
});

Vue,JS实现图片鼠标拖拽,滚轮放大缩小:

<template>
  <div>
    <img :src="src" :alt="alt" @click.stop="open()" :width="width" :height="height" title="点击查看图片"
         :id="'vc-imgself-img-'+attach">
    <div class="full-img" v-show="show" @contextmenu.prevent.stop="clearStyle">
      <img :src="currentImageSrc" alt="" class="img-state" :alt="alt || ''" @mousewheel="bigimg(this)" id="image" draggable="false"
           @mousedown.prevent="dropImage" style="position:fixed">
      <div class="btns row">
        <button type="button" name="button" class="btn btn-primary" @click.stop="leftRevolve()">向左旋转</button>
        <button type="button" name="button" class="btn btn-primary" @click.stop="rightRevolve()">向右旋转</button>
        <button type="button" name="button" class="btn btn-primary" @click.stop="close()">关闭</button>
        <button type="button" name="button" class="btn btn-primary" @click.stop="previousPage()">上一页</button>
        <button type="button" name="button" class="btn btn-primary" @click.stop="nextPage()">下一页</button>
      </div>
    </div>
  </div>
</template>
 
<script>
  import $ from 'jquery'
 
  export default {
    props: {
      src: {
        type: String
      },
      width: {
        default: 60
      },
      height: {
        default: 60
      },
      alt: {
        default: '图片加载失败'
      },
      attach: {
        type: String,
        default: 'name'
      },
      list: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        show: false,
        deg: 0,
        odiv: null,
        powerw: 1.0,
        container:null,
        positionX: null,
        positionY: null,
        powerh: 1.0,
        currentImageSrc:this.src
      }
    },
    ready(){
      const elementsToMount = document.getElementsByClassName("full-img");
      this.container = document.createElement('div');
      this.container.style.height = '0px'
      // 将要挂载的元素放入新创建的 div中
      for (let i = 0; i < elementsToMount.length; i++) {
        this.container.appendChild(elementsToMount[i]);
      }
      // 将新创建的 div 挂载到 body 上
      document.body.appendChild(this.container);
    },
    beforeDestroy(){
      // 销毁挂载的
      if (this.container && this.container.parentNode) {
        this.container.parentNode.removeChild(this.container);
      }
    },
    methods: {
      nextPage() {
        console.log(this.list)
        //当前图片,是最后一张图片
        if (this.currentImageSrc=== this.list[this.list.length - 1].f_overall_path) {
            this.currentImageSrc= this.list[0].f_overall_path
          } else {
          for (let i = 0; i < this.list.length; i++) {
            if (this.currentImageSrc=== this.list[i].f_overall_path) {
              this.currentImageSrc= this.list[i + 1].f_overall_path
              break
            }
          }
        }
 
      },
      previousPage() {
        console.log(this.list)
        //当前图片,是第一张图片
        if (this.currentImageSrc === this.list[0].f_overall_path) {
          this.currentImageSrc= this.list[this.list.length - 1].f_overall_path
        } else {
          for (let i = 0; i < this.list.length; i++) {
            if (this.currentImageSrc=== this.list[i].f_overall_path) {
              this.currentImageSrc= this.list[i - 1].f_overall_path
              break
            }
          }
        }
      },
      clearStyle(e){
        if (e === null) {
          return
        }
        this.odiv = document.getElementById('image')
        this.odiv.style.left = 500 + 'px';
        this.odiv.style.top = -150 + 'px';
      },
      bigimg() {
        if (event.wheelDelta > 0) {
          this.powerh = this.powerh * 1.15
          this.powerw = 1.15 * this.powerw
        } else {
          this.powerh = this.powerh * 0.85
          this.powerw = 0.85 * this.powerw
        }
        this.imgState()
      },
      dropImage(e) {
        if (e === null) {
          return
        }
        this.odiv = e.target;
        let disX = e.clientX - this.odiv.offsetLeft;
        let disY = e.clientY - this.odiv.offsetTop;
        document.onmousemove = (e) => {
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          this.positionX = top;
          this.positionY = left;
          this.odiv.style.left = left + 'px';
          this.odiv.style.top = top + 'px';
        };
        document.onmouseup = (e) => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      },
      open() {
        this.deg = 0
        this.powerw = 0.7
        this.powerh = 0.8
        $('.full-img').css({
          'transform': 'rotate(' + this.deg + 'deg) scale(' + this.powerh + ' ,' + this.powerw + ')'
        })
        $('.container').css({
          'opacity': '1'
        })
        this.show = true
      },
      close() {
        this.show = false
      },
      leftRevolve() {
        //tag
        this.deg -= 90
        this.imgState()
      },
      rightRevolve() {
        //tag
        this.deg += 90
        this.imgState()
      },
      imgState() {
        $('.img-state').css({
          'transform': 'rotate(' + this.deg + 'deg) scale(' + this.powerh + ' ,' + this.powerw + ')'
        })
 
      }
    },
  }
</script>
<style media="screen" scoped>
  .full-img {
    position: fixed;
    width: 100%;
    /*height: 1000px;*/
    overflow: hidden;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1070;
    opacity: 1;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
 
  .btns {
    position: fixed;
    bottom: 100px;
    height: auto;
  }
 
  .btns button {
    margin-right: 20px;
  }
 
  .img-state {
 
  }
</style>

调用组件:

<img-self-plus :width="120" :height="160" :src="row.url"></img-self-plus><

vue插件实现:

npm install vue-directive-zoom --save
<template>
  <div v-zoom:2="zoomOptions">
    <img src="path/to/your/image.jpg" alt="Zoomable Image">
  </div>
</template>
 
<script>
import Vue from 'vue';
import VueDirectiveZoom from 'vue-directive-zoom';
 
Vue.use(VueDirectiveZoom);
 
export default {
  data() {
    return {
      zoomOptions: {
        mouseWheel: true, // 开启鼠标滚轮缩放
        zoomMax: 5, // 最大缩放比例
        zoomMin: 1, // 最小缩放比例
        zoomStart: 1 // 初始缩放比例
      }
    };
  }
};
</script>

v-zoom:2指令用于放大图片,你可以通过调整zoomOptions中的参数来控制缩放的行为,如是否启用鼠标滚轮缩放,以及设置最大和最小缩放比例等。
请注意,vue-directive-zoom库可能不是最新的,并且可能不支持Vue 3。如果你使用的是Vue 3,可能需要寻找其他的解决方案。

react:
React中实现鼠标滚动来放大缩小图片,可以通过监听wheel事件来实现。

import React, { useState, useRef } from 'react';
import './App.css';
 
function App() {
  const [scale, setScale] = useState(1);
  const imageRef = useRef(null);
 
  const handleWheel = (e) => {
    e.preventDefault();
    const newScale = e.deltaY > 0 ? scale * 1.1 : scale / 1.1;
    setScale(newScale);
  };
 
  return (
    <div className="App">
      <div
        className="image-container"
        ref={imageRef}
        style={{ transform: `scale(${scale})` }}
        onWheel={handleWheel}
      >
        <img src="path_to_your_image.jpg" alt="Zoomable Image" />
      </div>
    </div>
  );
}
 
export default App;

我们使用了React的useState钩子来跟踪图片的缩放比例,并使用useRef钩子来获取对图片容器的引用。handleWheel函数会在鼠标滚轮滚动时被调用,并根据滚动的方向计算新的缩放比例。然后,我们通过设置容器的transform样式来应用缩放效果。

请确保在CSS中设置.image-container的overflow属性为hidden,以防止缩放后的图片溢出容器。

/* App.css */
.image-container {
  overflow: hidden;
  display: inline-block;
  /* other styles */
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/577211.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

让ThreadPoolExecutor无所遁形:Java线程池运行原理详解

ThreadPoolExecutor的核心工作原理 当我们在Java中讨论并发和多线程时&#xff0c;ThreadPoolExecutor 是不可或缺的一个类。在 java.util.concurrent 包下&#xff0c;该类负责管理线程池内的线程&#xff0c;包括线程的创建、执行、管理以及线程池的监控等。理解 ThreadPool…

玩转手机在AidLux上安装宝塔面板

AidLux&#xff0c;手机不用刷机、不用root&#xff0c;直接在手机应用市场就能下载使用。 1.4G的应用包&#xff0c;看起来挺大的&#xff0c;那是因为内嵌了一套完整的AIoT应用开发和部署平台。 不仅Android手机可以玩&#xff0c;华为的Harmony系统也可以使用。 使用它最主…

websocket爬虫

人群看板需求分析 先找到策略中心具体的数据。对应数据库中的数据 看看接口是否需要被逆向 点开消费者细分&#xff0c;可以找到人群包&#xff08;人群名称&#xff09; 点击查看透视 label字段分类: 在这里插入图片描述 预测年龄&#xff1a;tagTitle 苹果id&#x…

【Unity基础】TextMeshPro组件学习过程记录

目录 1.TextMeshPro组件渲染创建文本RTL Editor字体Font Asset字体加粗&#xff0c;下划线等字体大小控制字体颜色控制字体渐变控制字符间隔、单词间隔、行间距、段落间距控制WrappingUV映射控制代码 2.TextMeshPro组件AssetFace InfoGeneration Setting 3.使用Dynamic SDF Sys…

从C语言到C++过渡篇(快速入门C++)

目录 引言 命名空间 C 的输入输出&#xff08;cout & cin&#xff09; 输出 cout 输入 cin 缺省参数 函数重载 知识要点讲解 函数重载底层 引用& 内联函数 auto & nullptr 结语 引言 很多同学从C语言到C的转变不知从何下手&#xff0c;今天这篇文章主…

【MRI重建】Cartesian采样中data consistency 常规数据一致性实现(pytorch)

关于 在MRI重建中,data consistency 可以帮助加快MRI图像重建和减少模型重建带来的重建误差。 工具 方法实现 x_rec: 重建图像, (batch_size,2,H,W) mask: 欠采样模版,(batch_size,2,H,W) k_un: 真实欠采样采集数据, (batch_size,2,H,W) torch.view_as_complex: 将实数数据…

【Linux】HTTP协议2

欢迎来到Cefler的博客&#x1f601; &#x1f54c;博客主页&#xff1a;折纸花满衣 &#x1f3e0;个人专栏&#xff1a;题目解析 &#x1f30e;推荐文章&#xff1a;承接上文【Linux】HTTP协议1 目录 &#x1f449;&#x1f3fb;HTTP方法&#x1f449;&#x1f3fb;HTTP状态码&…

Swift - 流程控制

文章目录 Swift - 流程控制if-else2. while3. for3.1 闭区间运算符3.2 半开区间运算符3.3 for - 区间运算符用在数组上3.3.1 单侧区间 3.4 区间类型3.5 带间隔的区间值 4. switch4.1 fallthrough4.2 switch注意点 5. 复合条件6. 区间匹配、元组匹配7. 值绑定8. where9. 标签语句…

webpack中mode、NODE_ENV、DefinePlugin、cross-env的使用

本文讲的全部知识点&#xff0c;都是和webpack相关的。如果你之前有疑问&#xff0c;那本文一定能帮你搞清楚。 问题来源一般是类似下面代码&#xff08;webpack.json中&#xff09;&#xff1a; "scripts": {"dev": "cross-env NODE_ENVdevelopmen…

BUUCTF_[BSidesCF 2020]Had a bad day

[BSidesCF 2020]Had a bad day 1.一看题目直接尝试文件包含 2.直接报错&#xff0c;确实是存在文件包含漏洞 http://307b4461-36d6-443f-879a-68803a57f721.node5.buuoj.cn:81/index.php?categoryphp://filter/convert.base64-encode/resourceindex strpos() 函数查找字符串…

StarRocks x Paimon 构建极速实时湖仓分析架构实践

Paimon 介绍 Apache Paimon 是新一代的湖格式&#xff0c;可以使用 Flink 和 Spark 构建实时 Lakehouse 架构&#xff0c;以进行流式处理和批处理操作。Paimon 创新性地使用 LSM&#xff08;日志结构合并树&#xff09;结构&#xff0c;将实时流式更新引入 Lakehouse 架构中。 …

Docker基本操作 容器相关命令

docker run:运行镜像; docker pause:暂停容器&#xff0c;会让该容器暂时挂起&#xff1b; docker unpauser:从暂停到运行; docker stop:停止容器&#xff0c;杀死进程; docker start:重新创建进程。 docker ps&#xff1a;查看所有运行的容器及其状态&#xff0c;默认只展…

WildCard开通GitHub Copilot

更多AI内容请关注我的专栏&#xff1a;《体验AI》 期待您的点赞&#x1f44d;收藏⭐评论✍ WildCard开通GitHub Copilot GitHub Copilot 简介主要功能工作原理 开通过程1、注册Github账号2、准备一张信用卡或虚拟卡3、进入github copilot页4、选择试用5、选择支付方式6、填写卡…

实现SpringMVC底层机制(一)

文章目录 1.环境配置1.创建maven项目2.创建文件目录3.导入jar包 2.开发核心控制器文件目录1.流程图2.编写核心控制器SunDispatcherServlet.java3.类路径下编写spring配置文件sunspringmvc.xml4.配置中央控制器web.xml5.配置tomcat&#xff0c;完成测试1.配置发布方式2.配置热加…

创建Spring Boot项目

选择Maven Archetype,之后再Archetype选择webapp 两个都打勾 这是当前的打勾 这个是以后都默认勾上 打开对应的路径&#xff0c;用vscode打开settings.xml 加入国内源 阿里云 若没有此文件可上网查找 若jar包出现问题&#xff0c;可在repostitory文件内全删除 之后在Maven刷…

巴特沃斯滤波原理及代码实现(matlab详细过程版)

目录 一、算法原理1、原理概述2、参考文献 二、代码实现三、结果展示 本文由CSDN点云侠原创&#xff0c;原文链接。如果你不是在点云侠的博客中看到该文章&#xff0c;那么此处便是不要脸的爬虫与GPT。 一、算法原理 1、原理概述 巴特沃斯滤波器&#xff08;Butterworth filt…

主成分分析(PCA)在 Java 中的简单应用

在数据科学的众多工具中&#xff0c;主成分分析&#xff08;PCA&#xff09;是一种非常重要的统计技术&#xff0c;用于数据降维和模式识别。它通过提取数据中的关键特征来简化数据结构&#xff0c;从而帮助我们更好地理解数据集的主要变化因素。本文将介绍如何在 Java 编程环境…

CARLA (I)--Ubuntu20.04 服务器安装 CARLA_0.9.13服务端和客户端详细步骤

目录 0. 说明0.1 应用场景&#xff1a;0.2 本文动机&#xff1a; 1. 准备工作2. 安装 CARLA 服务端软件【远程服务器】3. 安装 CARLA 客户端【远程服务器】3.1 .egg 文件安装&#xff1a;3.2 .whl 文件安装&#xff1a;3.3 从Pypi下载Python package 4. 运行服务端程序5. 运行客…

arcgis js 4.x加载SceneLayer并实现基于属性查询定位及高亮

一、代码 <!DOCTYPE html> <html> <head><meta charset"utf-8" /><meta name"viewport" content"widthdevice-width, initial-scale1,maximum-scale1,user-scalableno"><title></title><link rel…

北京车展创新纷呈,移远通信网联赋能

时隔四年&#xff0c;备受瞩目的2024&#xff08;第十八届&#xff09;北京国际汽车展览会于4月25日盛大开幕。在这场汽车行业盛会上&#xff0c;各大主流车企竞相炫技&#xff0c;众多全球首发车、概念车、新能源车在这里汇聚&#xff0c;深刻揭示了汽车产业的最新成果和发展潮…
最新文章