使用Javascript进行Div布局

使用Javascript进行Div布局

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

     #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; }    
+
-

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

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

使用相对路径/例如

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

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

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

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

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

使用这样的东西:

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

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