<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>
修改div高度,可以直接给div的width赋值即可。
下面是小例子,仅供参考:
<style type='text/css'>#div2 {
width:200px
height:200px
background:red
border:1px solid black
}
</style>
<script>
function toGreen(){
var oDiv=document.getElementById('div2')
oDiv.style.width='300px'
oDiv.style.height='300px'
oDiv.style.background='green'
}
</script>
<body>
<div id='div2' onmouseover='toGreen()' >
</div>
超出固定高度显示滚动条,只要设置style属性中的overflowY="scroll"document.getElementById('scroll').style.overflowY="scroll"
获取div的高度,如果获取不到,可用下面的方法,一下方法是获取div的编辑完成后的高度:
/**
* obj:需要获取属性的html对象
* prop:需要获取的obj对象的属性
*/
function getCurrentStyle (obj, prop) {
if (obj.currentStyle) {
return obj.currentStyle[prop]
}
else if (window.getComputedStyle) {
propprop = prop.replace (/([A-Z])/g, "-$1")
propprop = prop.toLowerCase ()
return document.defaultView.getComputedStyle (obj,null)[prop]
}
return null
}
var div = document.getElementsByTagName("div")[0]
var height = getCurrentStyle(div,"height")