需求:朋友需要一个弹框,又不能引入太多插件代码,那就给他造一个弹框,也没有给我图片宽高,怎么破?

分析:html+css+js实现,利用absolute定位和css3:transform/translate实现未知宽高图片盒子始终水平垂直居中

效果:

实现代码:

css:

.boom{width: 100%;height: 100%;background: rgba(255,255,255,.5);position: fixed;z-index: 6666;left: 0;right: 0;top: 0;bottom: 0;display: none;}
.boombox{position: absolute;top: 50%;left: 50%;transform: translateX(-50%) translateY(-50%);width: 320px;} .boombox img{width: 100%;}
#boomClose{display: block;position: absolute;right: 0;top: 0;width: 35px;height: 35px;background: #000000;color: #fff;line-height: 35px;text-align: center;cursor: pointer;} 
@media screen and (max-width: 768px) { .boombox{width: 80%;} } 

html:

<div class="boom">
	<div class="boombox">
		<img src="http://a1.att.hudong.com/05/00/01300000194285122188000535877.jpg" alt=""/>
		<span id="boomClose">X</span>
	</div> 
</div> 

js:

window.onload = function(){
	var colse = document.getElementById("boomClose");
	var boom = document.getElementsByClassName("boom")[0];
	boomStart()

	function boomStart(){//显示
		boom.style.display = "block"
	}
	colse.onclick = function(){//隐藏
		boom.style.display = "none"
	}
}