用toggleMe脚本替换div

时间:2013-04-22 03:07:06

标签: javascript

我有三个链接的图像,每个图像都有不同的ID。我还有三个div引用相应的图像ID。我在页面中启用了toggleMe脚本并且正常工作。我的问题是如何更改此脚本,以便我不必再次单击该链接以折叠/展开内容?例如......如果我单击图像A,我希望图像A的内容扩展。然后,如果我单击图像B,我希望图像A的内容折叠,图像B展开,而不必再次单击图像A.或者,如果我单击图像C,我希望折叠先前的内容,并扩展图像C的新内容。

<script type="text/javascript">
function toggleMe(a){
  var e=document.getElementById(a);
  if(!e)return true;
  if(e.style.display=="none"){
    e.style.display="block"
  } else {
    e.style.display="none"
  }
  return true;
}
</script>

2 个答案:

答案 0 :(得分:1)

此功能称为accordian。 jquery ui有一个开箱即用的实现。 http://jqueryui.com/accordion/

把它放在脑海中:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script> $(function() {
    $( "#accordion" ).accordion();
    });
</script>

你的内容会有这样的结构:

 <div id="accordion">
    <h3>Section 1</h3>
    <div>
      <p>
        First
      </p>
    </div>
    <h3>Section 2</h3>
    <div>
      <p>
        Second 
      </p>
    </div>
    <h3>Section 3</h3>
    <div>
      <p>
        Third
      </p>
    </div>
  </div>

以下是一个示例:fiddle

答案 1 :(得分:1)

<script type="text/javascript">
function toggleMe(a){
  var allIds = ['one', 'two', 'three']; // store all of involved ids here
  var e=document.getElementById(a);
  if(!e)return true;
  for (var i = 0; i < allIds.length; i++) {
    if (allIds[i] != a) {
      document.getElementById(allIds[i]).style.display="none";
    }
  }
  if(e.style.display=="none") e.style.display="block";
  return true;
}
</script>