当前位置:首页 > 建站笔记 > 正文

html实现图片点击放大JS代码教程

今天用帝国仿了个模板,但是模板没有图片点击放大的功能,所以就把本站的图片放大相关的代码搬过去使用了,分享出来给大家。

如果你的网站不支持图片点击放大,让你觉得体验不是很好,那么可以跟我一起来完成它。

效果预览图:

image.png

一、在模板中引入css样式

CSS代码:

#outerdiv {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
  display: none;
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  background: rgba(120, 129, 147, .5);
  color: #fff;
  opacity: 1;
}
#bigimg {
  border: 5px solid rgba(255, 255, 255, 0.9);
  border-radius: 3px;
}
#outerdiv .caption-view {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 38px;
  background-color: rgba(0, 0, 0, .2);
  text-align: center;
}
#outerdiv .caption-view p {
  line-height: 38px;
  color: #fff;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

二、在你的模板中添加以下html

html如下:

 <div id="outerdiv"></div>
 <!-- 这段放在哪儿没什么要求,个人建议加在文章相关部分 -->

 <div class="bailiuli_com" >文章内容</div>
 <!-- 需要在你的文章DIV标签添加class="bailiuli_com" -->

三、引入JS代码

JS代码如下:

<script type="text/javascript">
$(function() {
	$(".bailiuli_com img").click(function() {
		var _this = $(this); 
		imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
	});
});
function imgShow(outerdiv, innerdiv, bigimg, _this) {
	var src = _this.attr("src"); 
	var alt = _this.attr("alt"); 
	$("#outerdiv").html('<div id="innerdiv" style="position:absolute;"><img id="bigimg" src="' + src + '" alt="' + alt + '"/></div><div class="caption-view"><p>' + alt + '</p></div>');
	$("<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.9; 
		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
		}); 
		$(outerdiv).fadeIn("fast"); 
	});
	$(outerdiv).click(function() { 
		$(this).fadeOut("fast");
	});
}
</script>

简单吧,在文章页面引入以上相关代码即可。今天就分享到此,如果对你看完还是有所疑问可以登陆后台反馈或者邮我。

发表评论