折叠并展开div而不会出现滚动条

时间:2019-03-06 03:50:50

标签: javascript jquery css

我正在使用Jquery尝试折叠div。要折叠的元素位于页面上的页脚上方,如下所示:

Initial state

页面上有一个按钮,当单击该按钮时,它会调用.animate()将div向下移至页脚上方,以使其看起来似乎在页脚后方滑动并看不见-基本上是向下折叠。

但是,当div移动到窗口底部之外时,浏览器的垂直滚动条将变为活动状态,直到我隐藏了折叠的div,即:

div collapses down behind footer

我希望看到div在没有垂直滚动条效果的情况下完全消失。

我还尝试为高度设置动画,但这会导致div从底部向上移动直到高度为零时缩小。

在不使垂直滚动条处于活动状态的情况下,使div向下折叠至零的诀窍是什么?我必须同时调整顶部和高度吗?

谢谢。

3 个答案:

答案 0 :(得分:0)

只需将overflow: hidden;和CSS设置为动态元素。像这样:

#yourDivElement{
   overflow: hidden;
}

那应该消除显示在div上的所有滚动条。参见:

https://www.w3schools.com/cssreF/pr_pos_overflow.asp

答案 1 :(得分:0)

使用jquery的slideToggle()方法。这是代码。

<body>
    <div class="wrapper">

        <div id="target-div">
            Collapse div down <br/>behind footer without vertical <br/>scrollbar being actived
        </div>
        <div>
            footer
        </div>
        <button id="clickable-button">Click here</button>
    </div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
    $('#clickable-button').on('click', function(e){
        $('#target-div').slideToggle();
    });

</script>
</body>

答案 2 :(得分:0)

使用JQuery .animate()方法发现以下工作。

/*
Set the "new" top position which we will animate to; this causes the
element to slide down while simultaneously adjusting the height
to zero, giving a collapse effect.  Note that if we did NOT adjust the
height down to zero and the element moves outside of the browsers
window, the browsers scrollbars would become active, which is NOT what
we want ...
*/

t = t + h;

elm.animate({ top: t, height: 0 }, 400, function () { /* Done */ });

要折叠元素:

t = t - h;

elm.animate({ top: t, height: h }, 400, function () { /* Done */ });

展开元素:

{{1}}

只要被动画化的div不在移动到浏览器窗口范围之外,上述方法都不会激活浏览器的垂直滚动条。