animate a div and expand from center

為{幸葍}努か 提交于 2019-12-12 13:33:11

问题


I have a simple code that expands a div horizontal and vertically from center, but it only expands to the left or to the bottom, I want it expands to both side(left=50px, right=50px) or (top=50px, bottom=50px) from center with total equal to 100px. here the code:

<!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>

Thank you.


回答1:


Hows this?

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/

I used margin-left and margin-top for the centering and animated the top: and left: values to make the box grow up and left as well as down and right.

You may have to add some extra CSS if you want the "Hello" to stay in the center of the box as well.



来源:https://stackoverflow.com/questions/6675491/animate-a-div-and-expand-from-center

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