提问者:小点点

如何在不改变位置的情况下更改div的宽度/高度?


我想复制这家伙做的但不使用画布。我想有一个div在我的页面的中心,并简单地增加宽度/高度/边界半径10px每秒。这工作得很好,但是由于某种原因,div越大,它向右下方移动的越多。圆圈不是静止不动的,它的中心位置随着它变大而改变。如何在不改变位置的情况下更改div的宽度/高度?

main.css

div {
  background-color: green;
  width: 100px;
  height: 100px;
  border-radius: 100px;
  position:absolute;
  top:50%;
  left:50%;
  margin-top:-50px; /* this is half the height of your div*/  
  margin-left:-100px; /*this is half of width of your div*/
}

index.html

<!DOCTYPE html>
  <head>
    <title>CircleTime</title>
    <link rel="stylesheet" href="main.css"></link>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
  <div></div>
  </body>
</html>

APP咖啡

incrementCircle = ->
  newSize = circle.height() + 10
  circle.height newSize
  circle.width newSize
  circle.css 'border-radius', newSize

$(document).ready ->
  window.circle = $("div")
  setInterval(incrementCircle, 1000);

共2个答案

匿名用户

在你的coffeescript中,像这样不断更新页边距:

incrementCircle = ->
newSize = circle.height() + 10
circle.height newSize
circle.width newSize
circle.css 'border-radius', newSize
circle.css 'margin-top', newSize/-2
circle.css 'margin-left', newSize/-2

$(document).ready ->
  window.circle = $("div")
  setInterval(incrementCircle, 1000);

http://jsfidle.net/sw0zn36e/5/

匿名用户

你也在改变页边距吗?

margin-top:-50px; /* this is half the height of your div*/    
margin-left:-100px; /*this is half of width of your div*/

只需将此添加到IncrementCircle

circle.css 'margin', -(newSize/2) + 'px, 0px, 0px, ' + -(newSize/2) + 'px'

相关问题