写一个滚动字的程序,有2个可总结的地方,第一个就是overflowL:hidden的用法,第二则是关于内联样式的取值问题。
下面是一段错误的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title> New Document </title>
<style type="text/css">
#f{width:200px;height:200px;border:1px solid;overflow:hidden}
#s{width:100px;height:100px;border:1px solid;margin-top:10px;}
</style>
</head>
<body>
<div id="f">
<div id="s"> 32132</div>
</div>
<script type="text/javascript">
var s=document.getElementById("s");
var st=parseInt(s.style.marginTop); // 这步是错的,事实上,如果是内联样式,s.style.marginTop是取不到值的。
function mo( ){
st-=10;
s.style.marginTop=st+"px"; // 虽然取不到值,但却可以这样赋值,也即可以设值,但不能取值(除非是行内样式)
}
setInterval("mo( )",1000);
</script>
</body>
</html>
两个办法可以解决这个问题:(1)把内联样式变成行内样式 (2)样式直接在js中定义
代码改成:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<style type="text/css">
#f{width:200px;height:200px;border:1px solid;overflow:hidden}
</style>
</head>
<body>
<div id="f">
<div id="s" style="width:100px;height:100px;border:1px solid;margin-top:0px;"> 32132</div> // 变成行内样式
</div>
<script type="text/javascript">
var s=document.getElementById("s");
s.style.marginTop=“10px”; // 直接在js中设值,这样s.style.marginTop也有了初始值,而不是undefined
var st=parseInt(s.style.marginTop);
function mo( ){
st-=10;
s.style.marginTop=st+"px";
}
setInterval("mo( )",1000);
</script>
</body>
</html>
总结:
(1)如果是行内样式,则可以object.style的方式直接获取值,但是如果是写成外联或者内联样式,这样是获取不到值的,会变成未定义。。。于是我们要么写成行内样式,要么直接在js中,用s.style.marginTop=“10px”的形式直接设置值,这是个很有意思的地方,虽然取不到值,但是却可以反向操作在js中去设置样式的值。
(2)父元素f,写了overflow:hidden,于是子元素或者本身内容超出的时候,超出部分会被隐藏,这就便是字体或者图移动到尽头的时候,会消失。
</html>