jQuery: List expands on page load

泄露秘密 提交于 2019-12-11 01:44:08

问题


I've been looking for something very simple: How to make a side navigation expand with animation on page load, but all the tutorial websites I usually go to don't seem to have it.

The closest I could find is this jQuery sample: http://codeblitz.wordpress.com/2009/04/15/jquery-animated-collapsible-list/

I've managed to strip down the list like so:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">
$(function(){
    $('li')
        .css('pointer','default')
        .css('list-style','none');
    $('li:has(ul)')
        .click(function(event){
            if (this == event.target) {
                $(this).css('list-style',
                    (!$(this).children().is(':hidden')) ? 'none' : 'none');
                $(this).children().toggle('slow');
            }
            return false;
        })
        .css({cursor:'pointer', 'list-style':'none'})
        .children().hide();
    $('li:not(:has(ul))').css({cursor:'default', 'list-style':'none'});
});
</script>

</head>

<body>
<fieldset>
    <legend>Collapsable List Demo</legend>
    <ul>
        <li>A - F</li>
        <li>G - M
            <ul>
                <li>George Kent Technology Centre</li>
                <li>Hampshire Park</li>
                <li>George Kent Technology Centre</li>
                <li>Hampshire Park</li>
            </ul>
        </li>
        <li>
            N - R
        </li>
        <li>S - Z</li>
    </ul>
</fieldset>

My question is:

Is there any way to make this list expand on page load instead of on click? I also don't need it to collapse at all; basically I need only the animating expansion.

Thank you for your time and advice. :)

edit Wonder if we could do the reversed effect of this...


回答1:


I would use setTimeout inside of $(document).ready() to animate the list in after a short period of time after the page has loaded:

var animateList = function() {
    $('li:has(ul)').each(function() {
        $(this).css('list-style', (!$(this).children().is(':hidden')) ? 'none' : 'none');
        $(this).children().toggle('slow');
    })
};

setTimeout(animateList, 500);

You can adjust the time period as necessary.

Example: http://jsfiddle.net/andrewwhitaker/7wQT5/




回答2:


Add this line after $('li:not(:has(ul))').css({cursor:'default', 'list-style':'none'});

 $('li:has(ul)').click();


来源:https://stackoverflow.com/questions/4590666/jquery-list-expands-on-page-load

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