上例子:<html>
<head>
<style type="text/css">
#container {
position: absolute;
top: 50px;
left: 50px;
width: 600px;
height: 500px;
border: 5px solid black;
background: white;
}
#child {
float: left;
width: 200px;
height: 100%;
border: 5px solid red;
background: green;
}
</style>
</head><body>
<div id="container">
<div id="child"></div>
</div>
</body>
</html>我的理解当子元素的高度设为100%时,不论是否加边框都不应该超出父容器的高度,但现在不是这样,和解?
如果css定义元素高度不包括边框的话,如何通过css解决这个问题?注意是不用js而纯用css解决哦。
<head>
<style type="text/css">
#container {
position: absolute;
top: 50px;
left: 50px;
width: 600px;
height: 500px;
border: 5px solid black;
background: white;
}
#child {
float: left;
width: 200px;
height: 100%;
border: 5px solid red;
background: green;
}
</style>
</head><body>
<div id="container">
<div id="child"></div>
</div>
</body>
</html>我的理解当子元素的高度设为100%时,不论是否加边框都不应该超出父容器的高度,但现在不是这样,和解?
如果css定义元素高度不包括边框的话,如何通过css解决这个问题?注意是不用js而纯用css解决哦。
追加一个问题:var w1 = document.getElementById("child").style.width;
alert(w1);
结果获取的w1无值。
只有显式的设置元素的width属性后才能获取值,难道通过css设置的width不能初始化通过js获取吗?
js获取 css中定义的值,需要“计算”一下。比如
<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312" />
<title></title>
<style>
</style>
</head>
<body>
<button id="btn">弹出层</button>
<script>
function $(o){return document.getElementById(o)}
var css = function(obj, attr, value){
switch(arguments.length){
case 2:
//二个参数, 如果第二个参数是对象, 批量设置属性
if(typeof attr == 'object'){
for(var i in attr){
obj.style[i] = attr[i];
}
}
//二个参数, 如果第二个参数是字符串, 读取属性值
else{
return obj.currentStyle? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr];
}
break;
case 3:
//三个参数, 单一设置属性
obj.style[attr] = value;
break;
default:
alert('参数有误!');
}
}
var o = $('btn');
alert( css(o, 'fontSize') )
css(o, {
fontSize: 123+'px',
color: 'red'
})
</script>
</body>
</html>