How to make it smoother with toggle ('slow')

折月煮酒 提交于 2019-12-05 23:36:52

For sliding down to work JQuery has to guess the eventual height of the element. When it gets this wrong you see a jump when the animation ends and the element is allowed to find its natural height.

Your problem is caused by the margins on the p tag which take up space in JQuery's original estimate, but are collapsed when the animation completes.

The solution is to either remove the margins on the p tags, to try to prevent the collapsing from happening by giving the .morepara div an explicit height, a border or some top/bottom padding, though both options have undesirable side effects.

you can use .children('p') in order to access <p> from <div>, but I suggest You to try the .slideToggle('slow') method instead of .toggle, still applying it to the <div> element. Generally, it fits well for the sort of thing You expect.

I'm not sure what's causing the jitter. My guess is it's an effect caused by fitting the paragraph into the div when the div's display attribute is changed from 'none' to 'block'. I've applied stanch's suggestion and come up with a working example that seems to work a little better.

<html>
<head>
<style type="text/css">
body {width: 660px; margin: 0 auto; }
.toppara{
background-color: #FF9; 
}
.morepara {
background-color: #fff; 
}

.togglebutn {
color: #900;
background-color: #FFF; 
}

</style>

</head>

<body>
    <div id="section1">
        <div class="toppara">
            <p>Content 1.</p> 
        </div>
        <div class="morepara">
            <p>
            Content 2. 
            </p>
        </div>
        <p class="togglebutn">
            <a>Show/Hide</a>
        </p>
    </div>

    <div id="section2">
        <div class="toppara">
            <p>Content 3.</p> 
        </div>
        <div class="morepara">
            <p>
            Content 4.
            </p>
        </div>
        <p class="togglebutn">
            <a>Show/Hide</a>
        </p>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('document').ready( function (){
    $('.morepara p').hide();
    $('.togglebutn a').click(
        function(){
            var parentpara = $(this).parent().prev().children();
            parentpara.toggle('normal');
        }
    );
});
</script>
</body>
</html>

Not sure if you have an answer to this yet but giving the DIV's that are being toggled a specific WIDTH actually worked for me. checked in FF & IE 7-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!