如何用js控制图片的图大宽度或是最大高度

JavaScript07

如何用js控制图片的图大宽度或是最大高度,第1张

这是很多网页前端设计者都面临的一个问题,今天通过收集整理,把我常用的方法贴出来,希望能对需要的同行朋友有点帮助~~首称贴一段js代码:<script type="text/javascript">var Image = {}function SetMiddle(image, height){/// <summary>重设图片大小后让图片相对于DIV居中</summary>if (typeof(image) == 'string') image = document.images[image] || document.getElementById(image)var div = image.parentNodeif(div.nodeName != "DIV"){div = div.parentNode}if(image.height >0 &&image.height <height){var marginTopVal= (height - image.height) / 2image.style.marginTop =parseInt(marginTopVal)+"px"///不加px,在火狐下不支持!}else{image.height = heightimage.style.marginTop = "0px"}}Image.Resize1=function(image,width,height){if(width==null||height==null)returnimage.removeAttribute('width')image.removeAttribute('height')var w = image.width, h = image.heightvar scalingW=w/width,scalingH=h/heightvar scaling = w / hif(scalingW>=scalingH){image.width=widthimage.height = width / scaling}else{image.height=heightimage.width = height*scaling}}function imgReSize(imgObj,w,h){Image.Resize1(imgObj,w,h)SetMiddle(imgObj,h)}</script>下面是具体的图片调用js函数的方法:onload=imgReSize(this,628,452)函数有三个参数,第一个就不用说了吧,每二个参数是说图片的最大宽度,第三个参数是表示图片的最大高度当图片的宽高任一个大于参数里设置的值的时候,图片就会等比例缩小,且位置相对于外面的容器左右居中多的不说了,你懂的~~~

js输入宽和高改变样式有两种情况:第一种情况就是宽高都写在样式表里,就比如#div1{width:120px}。这中情况通过#div1.style.width拿不到宽度,而通过#div1.offsetWidth才可以获取到宽度。

第二种情况就是宽和高是写在行内中,比如style="width:120px",这中情况通过上述2个方法都能拿到宽度。(什么是行内,就是直接在html标签上写样式)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>test</title>

<style>

#div {

width: 100px

height: 50px

border: 1px solid red

color: green

text-align: center

}

input {

width: 250px

}

</style>

<script>

function test() {

var a = document.getElementById('a')

var b = document.getElementById('b')

var div = document.getElementById('div')

div.style.width = a.value + 'px'

div.style.height = b.value + 'px'

}

</script>

</head>

<body>

<div>宽度(默认100px):<input type="text" id="a" placeholder="输入想要的宽度,点击测试看效果" /></div>

<div>高度(默认50px):<input type="text" id="b" placeholder="输入想要的高度,点击测试看效果" /></div>

<div><button onclick="test()">点击测试</button></div>

<div id="div">来改变我</div>

</body>

</html>