CSS-扩展子元素但保持父级的完整性。创建下拉列表

时间:2014-04-25 08:08:39

标签: javascript jquery css css3 drop-down-menu

我想创建一个下拉菜单(替换为Browswer&#39; <select>标记)。

所以,我在另一个<div>中创建了<div>来刺激<select>

但是,当我自动展开dropdown <div><div>时,也会扩展页面结构非常脏。

我的意思是,这是我实际代码的输出Original

当我点击展开结果是: enter image description here

但是我想要输出,当我点击展开时: enter image description here

这是我的代码:

<html>
<head>
    <title>Drop Down Demo</title>
    <style type="text/css">
    .ddown{
        width:250px;
        min-height: 25px;
        background: #aaa;
        border: 2px solid #777;
        color: #444;
        text-align: center;
        margin: 0px;
        display: inline-block;
    }
    .ddown a{
        display: none;
        width: 100%;
        height: 25px;
        text-align: left;
        color: #666;
        text-decoration: none;
        background: #ddd;
        border: 1px solid #999;
    }
    .ddownHead{
        display: inline-block !important;
    }
    .ddownItem{
        display: inline-block !important;
    }
    .ddownItem:hover{
        background: #33a;
        color: #fff;
    }
    .ddown_busy{
        background: #77a !important;
        border: 1px solid #558 !important;
        color: #fff !important;
    }
    </style>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    function toggle_expand_ddown(x){
        if($(x).closest("div").find("a").eq(0).hasClass("ddown_busy")){
            $(x).closest("div").find("a").eq(0).removeClass("ddown_busy");
        $(x).closest("div").find("div").each(function(){
            $(this).find("a").each(function(){
                $(this).removeClass("ddownItem");
            });
        });
        }
        else
        {
        $(x).closest("div").find("a").eq(0).addClass("ddown_busy");
        $(x).closest("div").find("div").each(function(){
            $(this).find("a").each(function(){
                $(this).addClass("ddownItem");
            });
        });
        }
    }
    </script>
</head>
<body>
    <div style="width:100%;height:25px;background:#aa0;border:2px solid #770;">
    <div class="ddown">
    <a class="ddownHead" href="#!" Onclick="toggle_expand_ddown(this);">Click to Expand</a>
    <div>
        <a href="#!">Item 1</a>
        <a href="#!">Item 1</a>
        <a href="#!">Item 1</a>
        <a href="#!">Item 1</a>
    </div>
    </div>
    This is Another Child in same Parent
    </div>
</body>
</html>

我也创造了小提琴

Here

我认为这只是因为CSS。但是欢迎任何建议。希望你能很快帮助我。

1 个答案:

答案 0 :(得分:1)

我认为您在打开和关闭<div>代码时遇到问题

我尝试将<div>标记添加到另一个孩子,并**css**

.div2{
        display: inline-block;
        position: absolute;
    }

<强> FIDDLE DEMO

通过将此css添加到主div:

或不使用绝对位置

overflow: visible;
vertical-align: top;

<强> FIDDLE DEMO 2

或将float:left添加到.ddown css

<强> FIDDLE DEMO 3

PS:我认为选项1是一种更好的做法,你只需要将每个孩子都放在<div>标签中