js实现滚动字幕程序所遇到的问题~~~

写一个滚动字的程序,有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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值