js计算图片宽高并且定位图片位置并且图片的宽高和定位不能超过父元

2020-03-26  本文已影响0人  yuki20

// 计算图片宽高并且定位图片位置并且图片的宽高和定位不能超过父元素的大小

functionposition(el,img) {

varimgwidth=img.width

varimgheight=img.height

varparent=el.parentNode

varparentwidth=parent.clientWidth||parent.offsetWidth

varparentheight=parent.clientHeight||parent.offsetHeight

if(imgwidth<=parentwidth) {

if(imgheight>=parentheight) {

imgwidth=imgwidth/ (imgheight/parentheight)

imgheight=parentheight

}

}else{

if(imgheight/ (imgwidth/parentwidth) <=parentheight) {

imgheight=imgheight/ (imgwidth/parentwidth)

imgwidth=parentwidth

}else{

imgwidth=imgwidth/ (imgheight/parentheight)

imgheight=parentheight

}

}

conststyle=el.style

style.position='absolute'

style.width=imgwidth+'px'

style.height=imgheight+'px'

style.left= (parentwidth-imgwidth) /2+'px'

style.top= (parentheight-imgheight) /2+'px'

style.visibility='visible'

}

exportdefaultfunctionpositionImg(el) {

el.removeAttribute('style')

if(el.getAttribute('noPosition') ==='') {

el.style.visibility='visible'

return

}

el.removeAttribute('style')

constimg=newImage()

img.onload=function() {

position(el,img)

}

img.src=el.src

}

上一篇 下一篇

猜你喜欢

热点阅读