使用Javascript进行Div布局

时间:2012-06-14 06:17:11

标签: javascript jquery css jquery-ui

使用Javascript进行Div布局

如果我点击+它应该是打开它再次点击 - 它应该关闭它工作正常但我需要的是,如果有更多的div如何在运行时处理它们。

<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script src="script.js"></script>

<style type="text/css">
#widnow{
width:100%;
border:solid 1px;
    float:left;
}

#title_bar{
background: #FEFEFE;
height: 25px;
width: 100%;
}
#button{
border:solid 1px;
width: 25px;
height: 23px;
float:right;
cursor:pointer;
}
.box{
height: 50%;
 width: 50%;
background: #DFDFDF;
float:left;
}
#title_bar1{
background: #FEFEFE;
height: 25px;
width: 100%;
}
#button1{
border:solid 1px;
width: 25px;
height: 23px;
float:right;
cursor:pointer;
}
.box1{
height: 50%;
width: 50%;
background:#C0C0C0;
float:left;
}

</style>
</head>
<body>

<div id="widnow">

<div class="box" >
<div id="title_bar">

        <div id="button">+</div>
</div>
</div>
<div  class="box1">
    <div id="title_bar1">
            <div id="button1">-</div>
    </div>
</div>
</div>

</body>

</html>

的script.js

  jQuery().ready(function() {

$("#button").click(function(){
if($(this).html() == "-"){
    $(this).html("+");
    $( ".box" ).css( "width","50%" );
    $( ".box1" ).show();

}
else{
    $(this).html("-");
    $( ".box" ).css( "width","100%" );
     $( ".box1" ).hide();
}

});


        });

请提出可以帮助我解决问题的想法。

3 个答案:

答案 0 :(得分:1)

不要对div的选择器进行硬编码。这样,您可以将其扩展到单个div之外。

使用类似的东西:

$('button').on('click',function(){
    $(this).parent('div').css({'width' : '50%'});
});

Example

答案 1 :(得分:0)

尝试为每个div元素提供不同的id,并给出类并使用id(#)而不是class(。)执行jQuery函数。

答案 2 :(得分:0)

使用相对路径/例如

$(this).parent().css("width","50%");

因此,您始终将包含已单击的(+/-)元素的框设置为样式。

你也需要调整你的$(“。box1”)显示/隐藏代码;正如Pulkit所说 - 你应该使用类而不是id。 (选择父级下面的类(“box1”)的子项为:

$(this).parent().children("#box1")