dom基础2 — 实现鼠标放大缩小查看图片功能
Posted popeyesailorman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dom基础2 — 实现鼠标放大缩小查看图片功能相关的知识,希望对你有一定的参考价值。
<script type="text/javascript"> "use strict"; var console = window.console; // var Event = require("./addEvent.js"); var dom = document.createElement(‘div‘); dom.style.width = ‘600px‘; dom.style.height = ‘600px‘; dom.style.border = ‘1px solid gray‘; dom.style.position = ‘absolute‘; dom.style.top = ‘0‘; dom.style.bottom = ‘0‘; dom.style.left = ‘0‘; dom.style.right = ‘0‘; dom.style.margin = ‘auto‘; dom.style.overflow = ‘hidden‘; document.body.appendChild(dom); dom.insertAdjacenthtml(‘afterbegin‘,‘<img src="https://qidian.qpic.cn/qidian_common/349573/9fb9627740f52f4addf43720928e683d/0"/>‘); var img = document.querySelector(‘img‘); img.style.width = ‘100%‘; img.style.height = ‘100%‘; img.style.objectFit = ‘cover‘; // 监听鼠标滚轮事件 var addEvent = (function(window, undefined) { var _eventCompat = function(event) { var type = event.type; if (type == ‘DOMMouseScroll‘ || type == ‘mousewheel‘) { event.delta = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3; } if (event.srcElement && !event.target) { event.target = event.srcElement; } if (!event.preventDefault && event.returnValue !== undefined) { event.preventDefault = function() { event.returnValue = false; }; } /* ......其他一些兼容性处理 */ return event; }; if (window.addEventListener) { return function(el, type, fn, capture) { if (type === "mousewheel" && document.mozFullScreen !== undefined) { type = "DOMMouseScroll"; } el.addEventListener(type, function(event) { fn.call(this, _eventCompat(event)); }, capture || false); }; } else if (window.attachEvent) { return function(el, type, fn, capture) { el.attachEvent("on" + type, function(event) { event = event || window.event; fn.call(el, _eventCompat(event)); }); }; } return function() {}; })(window); var num = 10; addEvent(dom, "mousewheel", function(event) { if (event.delta < 0) { console.log(‘鼠标向上滚了,图片缩小‘); num--; if (num <= 10) { num = 10; img.style.transform= ‘scale(1)‘; } else if (num > 10) { img.style.transform= ‘scale(‘ + num/10 + ‘)‘; console.log(num/10); } else { } } else { console.log(‘鼠标向下滚了,图片放大‘); num++; img.style.transform = ‘scale(‘ + num/10 + ‘)‘; console.log(num/10); } }); </script>
以上是关于dom基础2 — 实现鼠标放大缩小查看图片功能的主要内容,如果未能解决你的问题,请参考以下文章