JQuery Animate定义位置

时间:2016-09-21 09:24:15

标签: jquery html css

我正在尝试创建一个在顶部有标签(当前是按钮)的网页,当点击每个标签时,它将使用JQuery将div容器的扩展设置为网页中特定空间的动画。理想情况下,这应该是屏幕的中间位置,具体取决于最终div容器大小的大小。

起始点应该来自“选项卡式”按钮(再次,当前是一个按钮),但我无法将其设置为正确设置动画。

如果我使用相对位置,我无法将其设置到固定位置,例如屏幕中间。如果我使用绝对位置,它会从屏幕的左上角滚动,而不是从div容器的初始位置滚动。

有人能指出我正确的方向吗?我的完整代码如下(仅作为测试想法的草稿)。

由于

 $(document).ready(function(){
        $("#butbut1").click(function(){
            $("#div1").animate({
                left: '250px',
                top: '-50px',
                opacity: '1',
                height: '150px',
                width: '250px'
            });
        });
        $("#butbut2").click(function(){
            $("#div2").animate({
                left: '250px',
                top: '-50px',
                opacity: '1',
                height: '150px',
                width: '250px'
            });
        });
    });
 <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    
    </head>
    <body>

    <button id="butbut1">Start Animation1</button>
    <button id="butbut2">Start Animation2</button>
    <p>Text here, blah blah blah blah</p>

    <div id="div1" style="background:#98bf21;height:0px;width:0px;position:relative;overflow:hidden;opacity:0.5;">Lots of content in here that is much bigger than the actual box, hopefully it doesn't show at first but then it should show later on.</div>
    <div id="div2" style="background:orange;height:0px;width:0px;position:relative;overflow:hidden;opacity:0.5;">Lots of content in here that is much bigger than the actual box, hopefully it doesn't show at first but then it should show later on.</div>

    </body>
    </html>

制作一个JSFiddle来展示......

https://jsfiddle.net/dyceq9t8/1/

2 个答案:

答案 0 :(得分:0)

尝试将animate()中top的值从-50px更改为某个更高的值,如100px。

答案 1 :(得分:0)

如果您想在中间移动它,请尝试更改此

           position:'absolute',
            left: '40%',
            top: '50%',
           margin: '50px 0  0  50px'