这篇文章主要介绍JavaScript实现图片的放大缩小及拖拽功能的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
实现效果如下:
实现代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{width:400px;height:400px;overflow:hidden;position:relative;border:1px solid #000;} div img{position:absolute;height:100%;width:auto;cursor:move;} </style> </head> <body> <div id="div" onmousewheel="return bbimg(this)"><img id="img" border="0" src="img/zs.jpg" /></div> <script language="javascript"> var params = { zoomVal:1, left: 0, top: 0, currentX: 0, currentY: 0, flag: false }; //图片缩放 function bbimg(o){ var o=o.getElementsByTagName("img")[0]; params.zoomVal+=event.wheelDelta/1200; if (params.zoomVal >= 0.2) { o.style.transform="scale("+params.zoomVal+")"; } else { params.zoomVal=0.2; o.style.transform="scale("+params.zoomVal+")"; return false; } } //获取相关CSS属性 var getCss = function(o,key){ return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key]; }; //拖拽的实现 var startDrag = function(bar, target, callback){ if(getCss(target, "left") !== "auto"){ params.left = getCss(target, "left"); } if(getCss(target, "top") !== "auto"){ params.top = getCss(target, "top"); } //o是移动对象 bar.onmousedown = function(event){ params.flag = true; if(!event){ event = window.event; //防止IE文字选中 bar.onselectstart = function(){ return false; } } var e = event; params.currentX = e.clientX; params.currentY = e.clientY; }; document.onmouseup = function(){ params.flag = false; if(getCss(target, "left") !== "auto"){ params.left = getCss(target, "left"); } if(getCss(target, "top") !== "auto"){ params.top = getCss(target, "top"); } }; document.onmousemove = function(event){ var e = event ? event: window.event; if(params.flag){ var nowX = e.clientX, nowY = e.clientY; var disX = nowX - params.currentX, disY = nowY - params.currentY; target.style.left = parseInt(params.left) + disX+ "px"; target.style.top = parseInt(params.top) + disY+ "px"; if (typeof callback == "function") { callback((parseInt(params.left) || 0) + disX, (parseInt(params.top) || 0) + disY); } if (event.preventDefault) { event.preventDefault(); } return false; } } }; startDrag(document.getElementById("img"),document.getElementById("img")) </script> </body> </html>
以上是“JavaScript实现图片的放大缩小及拖拽功能的方法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。