简体   繁体   中英

Jquery slidedown not working

I'm pretty much new to the jquery library, so I was experimenting with some jquery functions. This is the code I wrote

<html>
<head>
<title>slide</title>

    <style>
        .outer  {

            width: 700px;
            height: 1000px;
            border: 2px dashed green;
            margin: 20px;
        }

        .box    {
            widht: 100px;
            height: 80px;
            border: 2px solid green;
            margin: 20px;
        }
    </style>

</head>
<body>
    <input type='button' id='btn' value='click' />
    <div class='outer'></div>
    <script type='text/javascript' src='jquery.js'></script>
    <script>
        $('#btn').click(function()  {
            $('.outer').prepend("<div class='box'></div>");
            $('.box').slideDown(3000);
        });
    </script>
</body> 

As you see, if i click the button, a new div prepends to the parent div. However the jquery slideDown function doesn't seem to have any effect but when I used slideUp, it worked as expected. So whenever i click the button the new div is created but no slidedown animation takes place. Am I missing something?

box cannot slide down, because the box is already being displayed.

Set display:none on your .box css rule, and you should get the effect you are after.

See Demo: http://jsfiddle.net/UDj5y/


If you don't wish to make changes to your CSS, you can use the following jQuery code instead:

$box = $("<div class='box'></div>");
$('.outer').prepend($box);
$box.hide().slideDown(3000);

See Demo: http://jsfiddle.net/UDj5y/1/

 $('#btn').click(function() { $box = $("<div class='box'></div>"); $('.outer').prepend($box); $box.hide().slideDown(3000); }); 
 .outer { width: 700px; height: 1000px; border: 2px dashed green; margin: 20px; } .box { width: 100px; height: 80px; border: 2px solid green; margin: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type='button' id='btn' value='click' /> <div class='outer'></div> 

Here's your solution:

http://jsfiddle.net/Rv2ap/

The reason it wasn't working is your box was visible when it was appended. This means the animation could not be run.

All you need to do is add display: none; to your css rules for .box

You should hide it:

.box {
  display: none;
}

If you don't do it, then box will appear immediately.

When you prepend the div it is automatically shown, so slideDown has nothing to do.

You have 2 options:

.box    {
            widht: 100px;
            height: 80px;
            border: 2px solid green;
            margin: 20px;
            display: none;
        }

or in jquery:

$('.box').hide().slideDown(3000);

see this fiddle: http://jsfiddle.net/GPhcc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM