Javascript滑入但无法滑出

时间:2012-12-08 14:13:02

标签: javascript javascript-events

我有这个简单的JavaScript代码应该支持div和div。它在滑入时非常有效。通过完美的工作可以轻松滑动div。但是,当您单击滑出时,div将从浏览器中消失。我不知道为什么,我找不到错。我的代码在这里

<!DOCTYPE html>
<html>
    <head></head>
    <body>

        <script>

            function slideIt()
            {
                var stopPosition = 50;
                var slidingDiv = "";
                slidingDiv = document.getElementById("d3");
                if (parseInt(slidingDiv.style.left) < stopPosition )
                {
                    slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
                    setTimeout(slideIt, 1);
                }
            }

            function slideOut()
            {
                var startPosition =-150;
                var slidingDiv = "";
                slidingDiv = document.getElementById("d4");
                if (parseInt(slidingDiv.style.left) > startPosition )
                {
                    slidingDiv.style.left = parseInt(slidingDiv.style.left) - 2 + "px";
                    setTimeout(slideOut(), 1);

                }
            }



        </script>
        <div id="d1" onclick="slideIt();">Slide in</div>
        <div id="d2" onclick="slideOut();">Slide out</div>
        <div id="d3" style="position: absolute; left:-150px; top:300px" >horizontally sliding div</div>
        <div id="d4" style="position: absolute; left:150px; top:300px">horizontally sliding div</div>


    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您不需要在第二次超时中调用slideOut。删除括号。

setTimeout(slideOut, 1);

以下是演示:http://jsfiddle.net/cctqf/