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

news2024/10/5 16:21:12

在这里插入图片描述

摘要:

最近弄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.coloradmin.cn/o/1627300.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

element 分页切换时:current-page无效 页数不会跟着一起切换

问题回溯&#xff1a;使用el-pagination组件 选择切换当前分页 页数为2 问题结果&#xff1a;el-pagination组件 当前页切换失败 一直都是 1&#xff0c;接口传参分页数据是2&#xff0c;打印当前分页也是2 解决方案1&#xff1a;使用 current-page参数 .sync 修饰符 解决方案2…

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

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

某赛通电子文档安全管理系统 多处 SQL注入漏洞复现

0x01 产品简介 某赛通电子文档安全管理系统(简称:CDG)是一款电子文档安全加密软件,该系统利用驱动层透明加密技术,通过对电子文档的加密保护,防止内部员工泄密和外部人员非法窃取企业核心重要数据资产,对电子文档进行全生命周期防护,系统具有透明加密、主动加密、智能…

函数模板与类模板初阶

如果要写一个交换函数&#xff0c;不同类型的话调用不同的交换函数&#xff0c;如果使用重载的话只能解决函数名相同但是会根据参数类型调用不同的函数。即使这样也依旧要写很多不同类型的swap交换函数 函数重载的交换函数 仔细观察会发现除了类型不同其他的函数结构什么的都一…

Postman 在 Linux 上的安装指南:简单快速开始使用

本文将介绍如何在 Linux 上安装 Postman 的详细步骤&#xff0c;Postman 支持的 Linux 的发行版包括&#xff1a;Ubuntu 14.04 及更高版本&#xff0c;Fedora 24&#xff0c;Debian 8 及更高版本。下面将介绍其具体的安装方法。 手动安装 Postman 的下载地址&#xff0c;下载…

一、Django 初识

简介 Django 是一个用于构建 Web 应用程序的高级 Python Web 框架。 版本对应 不同版本的django框架是基于特定的不同的python版本开发的&#xff0c;所以不同版本的django框架要正常执行功能只能安装特定的python版本 Django安装 安装 Django # 全局安装 pip install dj…

泰坦尼克号乘客生存情况预测分析2

泰坦尼克号乘客生存情况预测分析1 泰坦尼克号乘客生存情况预测分析2 泰坦尼克号乘客生存情况预测分析3 泰坦尼克号乘客生存情况预测分析总 背景描述 Titanic数据集在数据分析领域是十分经典的数据集&#xff0c;非常适合刚入门的小伙伴进行学习&#xff01; 泰坦尼克号轮船的…

ionic 中对Input输入框、searchbar进行solr检索

一、概述 Ionic 是一个用于开发跨平台应用程序的开源工具&#xff0c;可以使用 Angular、React 或 Vue 等前端框架。要在 Ionic 应用程序中实现实时与 Solr 通信&#xff0c;可以使用 HTTP 客户端&#xff08;如 Angular 的 HttpClient 或 Ionic 的 Native HTTP&#xff09;…

笔记:编写程序,绘制一个展示 2013~2019 财年阿里巴 巴淘宝+天猫平台的 GMV 的柱形图,实现过程如下:

文章目录 前言一、GMV 的柱形图是什么&#xff1f;二、编写代码总结 前言 编写程序。根据实例 2 的要求&#xff0c;绘制一个展示 2013~2019 财年阿里巴 巴淘宝天猫平台的 GMV 的柱形图&#xff0c;实现过程如下&#xff1a; &#xff08;1&#xff09; 导入 matplotlib.pypl…

Linux快速部署大语言模型LLaMa3,Web可视化j交互(Ollama+Open Web UI)

本文在个人博客同步发布&#xff0c;前往阅读 1 介绍 本文将介绍使用开源工具Ollama(60.6k⭐)部署LLaMa大模型&#xff0c;以及使用Open WebUI搭建前端Web交互界面的方法。 我们先来过一遍几个相关的概念&#xff0c;对这块比较熟悉的朋友可跳过。 1.1 大规模语言模型 大规…

从递归角度串联二叉树-图论-动态规划

一、深度理解二叉树的前中后序遍历 二叉树遍历框架如下&#xff1a; void traverse(TreeNode* root) {if (root nullptr) {return;}// 前序位置traverse(root->left);// 中序位置traverse(root->right);// 后序位置 }先不管所谓前中后序&#xff0c;单看 traverse 函数…

keytool,openssl的使用

写在前面 在生成公钥私钥&#xff0c;配置https时经常需要用到keytool&#xff0c;openssl工具&#xff0c;本文就一起看下其是如何使用的。 keytool是jdk自带的工具&#xff0c;不需要额外下载&#xff0c;但openssl需要额外下载 。 1&#xff1a;使用keytool生成jks私钥文件…

Office Word自动编号转文本

原理 使用office自带的宏功能&#xff0c;一键替换 过程 调出word的“开发工具”选项 文件->选项->自定义功能区->选中开发工具->确定 创建宏 开发工具->宏->创建宏 编写宏 在弹出来的框里&#xff0c;替换代码为 Sub num2txt() ActiveDocument.…

ArcGIS批量寻找图层要素中的空洞

空洞指的是图层中被要素包围所形成的没有被要素覆盖的地方&#xff0c;当图层要素数量非常庞大时&#xff0c;寻找这些空洞就不能一个一个的通过目测去寻找了&#xff0c;需要通过使用工具来实现这一目标。 一、【要素转线】工具 利用【要素转线】工具可以将空洞同图层要素处于…

电商技术揭秘三十五:智能风控功能架构浅析

相关系列文章 电商技术揭秘相关系列文章合集&#xff08;1&#xff09; 电商技术揭秘相关系列文章合集&#xff08;2&#xff09; 电商技术揭秘二十八&#xff1a;安全与合规性保障 电商技术揭秘二十九&#xff1a;电商法律合规浅析 电商技术揭秘三十&#xff1a;知识产权保…

WEB攻防-PHP特性-CMS审计实例

前置知识&#xff1a;PHP函数缺陷 测试环境&#xff1a;MetInfo CMS 函数缺陷导致的任意文件读取 漏洞URL&#xff1a;/include/thumb.php?dir 漏洞文件位置&#xff1a;MetInfo6.0.0\app\system\include\module\old_thumb.class.php <?phpdefined(IN_MET) or exit(No…

ElasticSearch语句中must,must_not,should 组合关系

前言&#xff1a; 在实际应用中&#xff0c;发现当bool中同时使用must和should 没有达到想要的想过&#xff0c;而是只展示了must中的命中数据&#xff0c;所以打算探究一下bool中 三种逻辑关系的组合。 上述查询语句只展示了must的结果&#xff0c;没有should中的结果&#…

Kafka 3.x.x 入门到精通(06)Kafka进阶

Kafka 3.x.x 入门到精通&#xff08;06&#xff09;——对标尚硅谷Kafka教程 3. Kafka进阶3.1 Controller选举3.2 Broker上线下线3.3 数据偏移量定位3.4 Topic删除3.5 日志清理和压缩3.7 页缓存3.8 零拷贝3.9 顺写日志3.10 Linux集群部署3.10.1 集群规划3.10.2 安装虚拟机(略)3…

MemFire解决方案-物联网数据平台解决方案

方案背景 随着各种通讯、传感技术发展&#xff0c;数据通讯成本的急剧下降&#xff0c;数以万亿计的智能设备&#xff08;智能手环、智能电表、智能手机、各种传感器设备等&#xff09;接入网络&#xff0c;并源源不断的产生海量的实时数据。这些海量数据的价值挖掘&#xff0…

15.Blender Eevee和Cycles渲染引擎对比

初步介绍 Eevee是实时渲染的引擎&#xff0c;会省略一些解算方式&#xff0c;尤其对光线和阴影 Cycles会考虑这些因素&#xff0c;所以会对光线和阴影的表达更加真实&#xff0c;有一个实时光线追踪的功能 Cycles渲染完之后&#xff0c;每移动一次画面&#xff0c;都会重新渲染…