- div内文本水平居中
- offsetWidth和width
- script方法调用传参
- offset在运动中的bug
div内文本水平居中:line-height 设置为div的height;
CSS内 line-height:行高;
设置div内内容水平居中,若div内有n行,则设置
line-height:div的width/n.
<style type="text/css">
#div1{width:300px;
height:300px;
border:1px solid black;
text-align:center;
line-height:300px;
}
</style>
<div id="div1">
文本内容水平居中
</div>
JavaScript中offsetWidth等和js直接获取元素的Width区别:
<style type="text/css">
#div3{width:100px; height:100px; background:#ccc;
float:left; padding:20px; border:10px solid;
}
</style> <script type="text/javascript">
<!--
var oDiv3=document.getElementById("div3"); console.log("Width="+getComputedStyle(oDiv3,null)["width"] );
// return oDiv3.currentStyle.width; // IE
//-->
</script>
小结:以width为例,js直接获取的元素是样式中设置的width,offsetWidth获取的width=this.padding*2+this.border*2+this.width。
方法在script内直接调用的处理方法:
<body>
<div id="div"> </div>
</body>
<script>
function fName(param){
console.log("运行函数");
}
var oDiv=document.getElementById("div");
// 如果无参数直接写函数名即可,不会在script中直接调用函数
// oDiv.onclick=fName;
// 如果有参数,如下方式会在script中直接调用,无论是否触发事件
// oDiv.onclick=fName(参数);
//处理方法:将事件放在匿名函数中即可
oDiv.onclick=function(){
fName(参数);
}
</script>
offset在运动中的bug
以下代码预期目标:div的width变窄。【忽略padding,使其为零】
①当div的border>=1,此代码使div的width变大;
②当div的border=0,此代码使div的width变小。
<body>
<style type="text/css">
div{height:100px; background:red; line-height:50px; border:1px solid;}
</style>
<div id="d1" style="width:200px;">
当div的border>=1,div变宽
当div的border=0, div变窄
</div>
</body>
<script type="text/javascript">
<!--
var d1=document.getElementById("d1");
var timer;
function move(obj){
timer=setInterval(function(){
obj.style.width=obj.offsetWidth-1+"px";
},30);
} // move
d1.onmouseover=function(obj){
move(this);
};
d1.onmouseout=function(){
clearInterval(timer);
}
//-->
</script>
注:offserWidth包含了div的border及padding,所以当border=1时,div.offsetWidth-parseInt(div.style.width)=2,那么【obj.style.width=obj.offsetWidth-1+”px”;】这行代码则使div的width变大。小结:运动中慎用offsetWidth。