参数说明
参数是一个数组或一个对象,可传多个
parent img的父元素(针对谁居中)
img img元素
imgWidth 图片的物理宽
imgHeight 图片的物理高
delay 窗口大小改变时,触发resize事件的间隔(截流)
调用方法
new TileImg([{
parent: document.getElementById('img-parent'),
img: document.getElementsByClassName('img')[0],
imgWidth: 6000,
imgHeight: 4000,
delay: 500, // 默认10
}])
html
<div id="img-parent">
<img class="img" src="./images/f.jpg" alt="">
</div>
css
*{
padding: 0;
margin: 0;
}
html,body{
width: 100%;
height: 100%;
}
#img-parent {
width: 100%;
height: 100%;
overflow: hidden;
}
js
function TileImg(params){
let pt = Object.prototype.toString.call(params)
if (pt === '[object Object]') {
this.params = [params]
} else if(pt === '[object Array]') {
this.params = params
}
this.setArgs()
}
TileImg.prototype.setArgs = function(){
// 分开
var allObj = []
for(var i = 0; i < this.params.length; i++) {
var obj = {}
obj.p = this.params[i].parent
obj.g = this.params[i].img
obj.gw = this.params[i].imgWidth
obj.gh = this.params[i].imgHeight
obj.delay = this.params[i].delay || 10
obj.plh = document.createElement('div')
obj.plh.setAttribute('style', ' 100%; height: 0; padding-bottom:'+ obj.gh / obj.gw * 100 +'%;')
obj.p.appendChild(obj.plh)
obj.timer = true
this.setImg.call(obj, this)
allObj.push(obj)
}
var that = this
window.addEventListener('resize', function(){
for(var i = 0; i<allObj.length; i++){
that.setImg.call(allObj[i], that)
}
}, false)
}
TileImg.prototype.setImg = function(that){
// var that = this
if(this.timer) {
this.timer = false
var _this = this
setTimeout(function(){
_this.timer = true
}, this.delay)
this.ih = this.plh.clientHeight
this.ph = this.p.clientHeight
this.gs = 'width'
this.ih < this.ph && (this.gs = 'height')
that.setStyle.call(this)
}
}
TileImg.prototype.setStyle = function () {
this.p.style.position = 'relative'
this.g.style = ''
this.g.style.position = 'absolute'
this.g.style.left = '50%'
this.g.style.top = '50%'
this.g.style.transform = 'translate(-50%, -50%)'
this.g.style[this.gs] = '100%'
}