jQuery slideDown()向下移动下面的所有内容.如何防止这种情况

jQuery slideDown() moves everything below downwards. How to prevent this?

本文关键字:何防止 情况 slideDown 移动 jQuery      更新时间:2023-09-26

我对jQuery slideDown()动画有一个小问题。当这个slideDown()被触发时,它也会向下移动下面的所有东西。

如何使<p>下面的所有东西都滑下来,保持静止?

注意:

我更喜欢对<p>元素或slideDown调用或其他内容进行更改的解决方案。因为在我的实际页面中,<p>下面有很多东西被向下滑动,所以更改/重新排列所有这些东西对我来说需要更长的时间~

演示@JSFiddle:http://jsfiddle.net/ahmadka/A2mmP/24/

HTML代码:

<section class="subscribe">
    <button id="submitBtn" type="submit">Subscribe</button>
    <p></p>
</section>
<div style="padding-top: 30px;">
    <table border="1">
        <tr>
            <td>This table moves</td>
            <td>down when</td>
        </tr>
        <tr>
            <td>slideDown()</td>
            <td>is activated !</td>
        </tr>
    </table>
</div>

JavaScript:

$(function () {
    $("#submitBtn").click(function (event) {
        $(".subscribe p").html("Thanks for your interest!").slideDown();
    });
});

CSS:

.subscribe p {
    display: none;
}

您可以将该元素position作为absolute:

.subscribe p {
    display: none;
    position : absolute;        // add this line
}

演示:http://jsfiddle.net/A2mmP/25/

现有代码的情况是,元素从display:none;开始,所以它根本不会占用任何空间,直到您将其滑入并更改为display:block,从而向下移动以下元素。

position:absolute中,它不会占用空间,而是重叠:事实上,在我更新的小提琴版本中,你可以看到下面的桌子有轻微的重叠——你显然可以调整桌子上的边距或其他任何东西,使其符合你想要的方式。

您所需要的只是提供.subscribe.的固定高度

.subscribe {
    height: 50px;
}
.subscribe p {
    margin: 0px;
    display: none;
}

这是jsFiddle:http://jsfiddle.net/xL3R8/

解决方案

我们将滑动元素放在具有固定宽度的div元素中,以防止文档流受到滑动事件的影响。

HTML

<section class="subscribe">
    <button id="submitBtn" type="submit">Subscribe</button>
    <!-- this is the modified part -->
    <div><p></p></div>
</section>

CSS

.subscribe div
{
    /* We force the width to stay a maximum of 22px */
    height:22px;
    max-height:22px;
    overflow:hidden;
}
.subscribe div p {
    display: none;
    /* We reset the top margin so the element is shown correctly */
    margin-top:0px;
}

实时演示

问题是你的CSS,当它滑入时,它会呈现为块并向下推其他元素。将其设置为绝对位置,并将z索引更改为在前面或后面。

.subscribe p {
display: none;
position: absolute;
z-index: 100;

}

Fiddle

 .subscribe p {
     display: none;
     margin :0px;    
 }

IMO一个好的UI实践是删除订阅按钮,然后在那里显示一条消息,如下所示:"万岁!你已经订阅了"例如http://jsfiddle.net/UvXkY/

$(function () {
$("#submitBtn").click(function (event) {
    $("#submitBtn").slideToggle('slow', function(){
        $(".subscribe p").html("Thanks for your interest!").slideDown();    
    });
});

});

您面临的实际问题是display:none,它将删除元素p 的空间

其中作为visiblity:hidden和显示将获得这个问题的

即使它不会给出正确的slideDown效果,所以你可以使用绝对位置并为p元素保留一些空间,这也会解决你的问题。

解决方案之一

.subscribe p {
   position:absolute;
    display:none;
}
.subscribe
{
    position:relative;
    height:50px;
}

FIDDLE演示

相关文章: