js点击放大图片效果
JS 2023-02-01
实现网页中部分图片点击后放大效果,通过js实现图片放大效果。
原始效果;
点击后效果:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Document</title><style>ul,li{margin:0;padding:0;list-style: none}#box{width:600px; height:200px;margin:20px auto;position: relative;}ul li{float: left;width:200px;height:200px;}img{width:100%;height:100%;cursor:zoom-in;}.mark{width:600px;height:400px; background:#000;opacity: 0.5;}span{position: absolute;width:20px;height:20px;left:450px;top:50px; background: #fff;text-align: center;}</style></head><body><div id='box'><ul><!--插入图片--><li><img src="img/1.jpg" alt=""></li><li><img src="img/2.jpg" alt=""></li><li><img src="img/3.jpg" alt=""></li><li><img src="img/4.jpg" alt=""></li><li><img src="img/5.jpg" alt=""></li><li><img src="img/6.jpg" alt=""></li></ul></div><!-- 遮罩区域(先将div隐藏)--><div id="back-curtain" style="position:fixed;top:0;left:0;background:rgba(0,0,0,0.5);z-index:998;width:100%;display:none;"><!--放大后的图片--><div id="imgDiv" style="position:absolute;"><img id="bigImg" style="cursor:zoom-out;" src="" /></div></div><script src="js/jquery-1.8.3.min.js"></script><script type="text/javascript">// 图片点击放大var box=document.getElementById('box');var lis=box.getElementsByTagName('img');for(var i=0;i<lis.length;i++){lis[i].onclick=function(){imgShow("#imgDiv", "#bigImg", $(this), "#back-curtain");}}function imgShow(imgDiv, bigImg, _this, curtain) {// 图片路径var src = _this.attr("src");$(bigImg).attr("src", src);// 加载图片,获取当前点击图片的真实大小$("<img/>").attr("src", src).load(function(){var windowWidth = $(window).width();var windowHeight = $(window).height();var realWidth = this.width;var realHeight = this.height;var imgWidth, imgHeight;var scale = 0.8;if (realHeight > windowHeight * scale) {imgHeight = windowHeight * scale;imgWidth = imgHeight / realHeight * realWidth;if (imgWidth > windowWidth * scale) {imgWidth = windowWidth * scale;}} else if (realWidth > windowWidth * scale) {imgWidth = windowWidth * scale;imgHeight = imgWidth / realWidth * realHeight;} else {imgWidth = realWidth;imgHeight = realHeight;}$(bigImg).css({'width':imgWidth});//计算图片与窗口左边距var left = (windowWidth - imgWidth) / 2;//计算图片与窗口上边距var top = (windowHeight - imgHeight) / 2;// 图片位置$(imgDiv).css({'top':top, 'left':left});// 图片淡入$(curtain).fadeIn("fast");// 遮罩效果$(curtain).css({'position':'fixed','overflow-y':'auto','width':'100%','height':'100%','z-index':'998'}).show();});// 点击图片或遮罩,图片淡出$(curtain).on('click', function(){$(this).fadeOut("fast");});}</script></body></html>
上一篇:没有了