摘要:
最近弄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; //每次滚动加减10if (zoom > 0)obj.style.zoom = zoom + '%'; //更改后的zoom赋值给objreturn 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元素,接下来从滚轮事件中获取了用户的滚动方向,然后计算出当前图片的放大/缩小后的宽度和高度,并将其重新赋值给了图片元素。 注意在这个代码中我们同时监听了
mousewheel和
DOMMouseScroll`这两种不同浏览器的滚轮事件,以保证代码能够在不同的浏览器中正常运行。
$(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_pathbreak}}}},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_pathbreak}}}},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.15this.powerw = 1.15 * this.powerw} else {this.powerh = this.powerh * 0.85this.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 = 0this.powerw = 0.7this.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() {//tagthis.deg -= 90this.imgState()},rightRevolve() {//tagthis.deg += 90this.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"><divclassName="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 */
}