3

我的世界

  • jQuery 1.9.1
  • jQuery UI 1.10.3,虽然我的jsfiddle 示例使用 UI 1.9.2 并且似乎工作正常。

我的问题

stackoverflow上有很多类似的问题,但我找不到合适的答案。基本上我有一个 jQuery 手风琴,在页面加载时不会显示,它的显示可以block通过 jQuery.toggle()方法更改。切换工作正常,但除非heightStyle: "fill"在加载页面时显示父 div,否则不会适当地填充空间,这是我不想要的。

我对解决方案的尝试

  • 在文档末尾和<head>部分中重新定位脚本。
  • 重新排列切换发生的顺序:有第二个元素 ,#map它在打开手风琴的同时被关闭,反之亦然。
  • 因为我不完全确定手风琴是否首先需要父容器,所以我尝试了几种方法:切换#accordiondiv、它的父 div 和两个 div。
  • 为了更好地衡量,我还尝试了该.accordion( "refresh" )方法,以及在父 div 和#accordion. 没有汤。
  • 父容器的各种 CSS 定位和#accordion.
  • 深入了解 jQuery.js。鉴于我在 javascript 方面的新手经验,这并没有持续多久。说真的,不得不查一下这个东西===。:)

我的,这很有趣

当单击切换按钮隐藏手风琴并#map再次显示时,您可以看到heightStyle: "fill"实际工作一秒钟!我减慢了 jsfiddle 中的转换持续时间,以便更容易看到它。

所以,无论什么使正确的高度计算成为heightStyle: "fill"可能,这就是我需要一直发生的事情。任何建议表示赞赏!

js小提琴:http: //jsfiddle.net/Y8B4W/1/

HTML

<div>
  <div class="page-header">
    <div id="menu">Menu</div>
  </div>
  <div id="leftpanel">
    <div id="accordion">
      <h3>Heading 1</h3>
      <div>
        <p>...</p>
      </div>
      <!-- ...repeat for three more headings/sections... -->
    </div><!--accordion-->
  </div><!-- #leftpanel -->
  <div id="map"></div>
</div>

CSS

body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
    color: #000;
}
.page-header {
    width: 100%;
    height: 3em;
    background: gray;
}
#menu {
    font-size: 1em;
    margin: 0.5em;
    font-weight: bold;
    cursor: pointer;
}
#leftpanel {
    display: none;
    background: blue;
    padding: 0;
    margin: 0;
    position: absolute;
    top: 3em;
    left: 0;
    bottom: 0;
    width: 100%;
}
#map {
    position: absolute;
    bottom: 0;
    top: 3em;
    width: 100%;
    background: yellow;
    line-height: 1.5em;
}

Javascript

$( "#accordion" ).accordion({
    heightStyle: "fill",
    collapsible: true
});
$( "#menu" ).click(function() {
    $( "#map" ).toggle({
        duration: 2000
    });
    $( "#leftpanel" ).toggle({
        duration: 2000
    });
    $( "#accordion" ).accordion( "refresh" );
});
4

2 回答 2

2

这是一种廉价而厚颜无耻的黑客行为,但它确实有效。基本上,由于其属性,当页面加载时(即 jQuery 分配手风琴高度时) ,父 div 的高度#leftpanel没有被正确计算。display:none所以,我只是自己抓住了高度并#accordion在添加手风琴功能之前手动分配它,这就像做梦一样:

$( "#menu" ).click(function() {
    $( "#map" ).toggle( "slow" );
    if ($( "#leftpanel" ).css("display") == "none") {
        $(function() {
            $( "#leftpanel").css("display", "block");
            var accordHt = $( "#leftpanel" ).css( "height" );
                $( "#accordion").css("height", accordHt);
            $( "#accordion" ).accordion({
                heightStyle: "fill",
                collapsible: true
            });
       });
    };
});

如果您想知道为什么使用“if”语句而不是直接分配属性,那是因为#leftpanel当页面加载到屏幕宽度为 800 像素及以上时,我在其中显示了一个媒体查询。

来吧,小提琴:http: //jsfiddle.net/72rw2/

于 2013-10-23T18:48:42.423 回答
1

另一种方法是在更改后调用刷新display:none

$( "#menu" ).click(function() {
    $( "#leftpanel").css("display", "block");
    $( "#accordion" ).accordion( "refresh" );
}
于 2020-08-15T02:47:29.803 回答