您的位置:首页 - 代码 - CSS教程 - 正文
如何制作可控制显示或隐藏的伸缩式DIV+CSS新闻列表?
作者:未知 文章来源:互联网 发布时间:2007-01-05 20:43:56
  新闻列表是我们在页面制作中最常用的元素之一,根据项目的需要我们要求对这个新闻列表可控,可以点击显示或隐藏。用DIV+CSS该如何制作呢?

  HTML元素有display属性,当display:none的时候,这个元素就不可见了。我们可以根据这一特性来构思,而元素的具体控制我们可以通过javascript脚本来实现。

  我们看下面的javascript脚本:
程序代码1
var flag=true;
function showNews(){
    var fimg=document.getElementById("btnOpen");
    var obj=document.getElementById("newsList");
    if(flag){
        obj.style.display="none";
        fimg.src="open2.gif";
        flag=false;
    }else{
        obj.style.display="";
        fimg.src="open1.gif";
        flag=true;
    }
}

  两种状态,两个图片,在第一状态中,我们设置了元素display:none。即隐藏了HTML元素。
  我们看下面的CSS代码和XHTML代码:
程序代码2
*{
    margin:0;padding:0;
}
body{
    background-color:#fff;font-size:12px;text-align:left;
}

#topNews{
    width: 300px;
    margin: 60px auto 0 auto;
    text-align:left;
    padding-bottom:10px;
    background: #fff url(new_bottom.gif) bottom no-repeat;
}
#newsList {
    width:100%;
    height:100px;
    list-style:none;
    padding-top:5px;
    background: #fff url(new_bg.gif) repeat-y;
}
#newsList li{
    text-indent:16px;
    font-size:12px;
    line-height: 20px;
    float: left;
    width:280px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;        
}
#topNews h1{
    background: #fff url(new_top.gif) no-repeat;
    height:33px;
    font-size:12px;
}
#btnOpen{
    margin-top:15px;
    margin-left:12px;
    display: inline;
    cursor:pointer;
}
#topNews a{
    padding-left:12px;
    text-decoration: none;
    color:#c00;
}
#topNews a:hover{
    color:#f60;
    text-decoration: underline;
}

程序代码3
<div id="topNews">
    <h1>
        <img id="btnOpen" src="open1.gif" alt="|折叠|展开|" onclick="showNews()" />
        <span>我爱CSS resday.com</span>
    </h1>
    <ul id="newsList">
        <li><a href="http://www.resday.com/" title=""></a></li>
        <li><a href="http://www.resday.com/" title=""></a></li>
        <li><a href="http://www.resday.com/" title=""></a></li>
        <li><a href="http://www.resday.com/" title=""></a></li>
        <li><a href="http://www.resday.com/" title=""></a></li>
        <li><a href="http://www.resday.com/" title=""></a></li>
    </ul>
</div>

  请大家注意看两个地方:

  1、id="btnOpen" src="open1.gif" alt="|折叠|展开|" onclick="showNews()" 这是切换的“开关”,点击触发javascript事件。

  2、ul id="newsList" 这是控制的内容区域,应用javascript控制其css的display属性。当正常显示时,属性值为空;我们需要隐藏时,其实属性值为none。

  我们看下面的最终运行效果:
 提示:您可以先修改部分代码再运行

  在实际应用时,我们可以将javascript写到一个单独的文件中,在xhtml文件中调用就可以了。CSS也同样写入外部文件,link调用即可。

  对这个问题的解决,或许您有更好的办法,欢迎您来我的主页resday.com与我交流。大家共同进步。
热门文章
最新文章