【问题标题】:Div layout using Javascript使用 Javascript 的 div 布局
【发布时间】:2012-06-14 14:33:47
【问题描述】:

使用 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();
}

});


        });

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

【问题讨论】:

    标签: javascript jquery css jquery-ui


    【解决方案1】:

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

    使用这样的东西:

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

    Example

    【讨论】:

      【解决方案2】:

      使用相对路径/例如

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

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

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

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

      【讨论】:

        【解决方案3】:

        尝试为每个 div 元素赋予不同的 id,同时赋予类并使用 id (#) 而不是类 (.) 执行 jQuery 函数

        【讨论】:

        • 如何使用 javascript 提供 id
        猜你喜欢
        • 1970-01-01
        • 2015-07-16
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多