【问题标题】:animate a div and expand from center为 div 设置动画并从中心展开
【发布时间】:2014-10-08 21:30:14
【问题描述】:

我有一个简单的代码,可以从中心水平和垂直扩展一个 div, 但它只扩展到左侧或底部,我希望它从中心扩展到两侧(left=50px,right=50px)或(top=50px,bottom=50px),总计等于100px。 这里是代码:

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
    background-color:#bca;
    background: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    background-repeat: no-repeat;
    background-position: center center;
    border:1px solid green;
    padding:10px;
}
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="go">&raquo; Run</button>

<div id="block">Hello!</div>
<script>


$("#go").click(function(){
  $("#block").animate({
    width: "100px",
    height: "100px",
    opacity: 0.6,
  }, 1500 );
});
</script>

</body>

谢谢。

【问题讨论】:

    标签: css animation center expand


    【解决方案1】:

    这个怎么样?

    HTML

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
        <button id="go">&raquo; Run</button>
        <div id="block">Hello!</div>
    </body>
    

    CSS

    div {
        background-color:#bca;
        background: #fff;
        position: absolute;
        top: 0px;
        left: 0px;
        margin-left: 50%;
        margin-top: 50%;
        background-repeat: no-repeat;
        background-position: center center;
        border:1px solid green;
        padding:10px;
    }
    

    jQuery

    $("#go").click(function(){
        $("#block").animate({
            width: "100px",
            height: "100px",
            top: "-50px",
            left: "-50px",
            opacity: 0.6,
        }, 1500 );
    });
    

    http://jsfiddle.net/theguywholikeslinux/87f4Y/

    我使用 margin-left 和 margin-top 进行居中并动画 top: 和 left: 值以使框向上和向左以及向下和向右生长。

    如果您希望“Hello”也留在框的中心,您可能需要添加一些额外的 CSS。

    【讨论】:

    • 哇,太酷了,这就是我想要的!谢谢你,你拯救了我的一天~
    • @vike 如果您按下向上和向下箭头旁边的勾号按钮,那么您可以将我的答案标记为“已接受”,每个人都会知道您的问题已经解决以及解决方案是什么。
    猜你喜欢
    • 2018-08-10
    • 2018-07-28
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    相关资源
    最近更新 更多