将水平宽度大于窗口宽度的 div 居中



我有一个列表,它在页面上以分层树结构向外展开。我需要在页面加载时将列表居中,允许用户左右滚动。

<body>
  <div class="container">
    <div class="tree">
      <ul>
        <li>
          <ul>
            <li>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</body>

因此,假设主体的窗口大小或内部宽度为1000px。假设 .tree 是 2000px。我需要加载页面,使 .tree 向左 -500px,水平滚动条居中,以便用户可以左右移动以查看 .tree 的所有 2000px。

我失败的尝试

    $innerWidth = $('body').innerWidth();
    $treeWidth = $(".tree ul:first").width();
    $(".tree").css("width", $treeWidth);
    if ($treeWidth > $innerWidth) {
        $treeDiff = ($treeWidth - $innerWidth) / 2;
        $(".container").css({"min-width" : $treeWidth, "margin-left" : -$treeDiff, "width" : $treeWidth});
    } else {
        $(".container").css({"min-width" : $treeWidth, "width" : $innerWidth});
    }

导致树传播的事件中包装以下内容:

var newWidthDec = parseFloat($('.tree').css('width').replace('px',''));
var newWidth = Math.ceil(newWidthFloat);
window.scrollTo((newWidth/2),0);

请注意,滚动条的左端将靠近中心页面。

最新更新