【问题标题】:How can I change the width/height of a div without changing position?如何在不更改位置的情况下更改 div 的宽度/高度?
【发布时间】:2015-01-14 22:24:57
【问题描述】:

我想duplicate what this guy did 但不使用画布。我想在我的页面中心有一个 div 并简单地将宽度/高度/边框半径每秒增加 10 像素。这工作得很好,但由于某种原因,div 越大,它移动到右下方的次数就越多。圆并没有静止不动,它的中心位置随着它变大而改变。如何在不更改位置的情况下更改 div 的宽度/高度?

ma​​in.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.coffee

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

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

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    在你的咖啡脚本中,像这样不断更新边距:

    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://jsfiddle.net/sw0zn36e/5/

    【讨论】:

    • 这行得通,但在第一次迭代中,圆圈“跳”到右边。之后它保持静止,这很好。无论如何,谢谢!
    • Nm,我自己修好了。非常感谢!
    【解决方案2】:

    您是否也在更改边距?

    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'
    

    【讨论】:

      【解决方案3】:

      这可能是一个 CSS 问题。

      试试这个:

      div {
        background-color: green;
        width: 100px;
        height: 100px;
        border-radius: 100px;
        margin: 0 auto;
      }
      

      【讨论】:

        【解决方案4】:

        切换到margin: 0 auto; 有效。请参阅此代码笔:http://codepen.io/anon/pen/myWBZW

        【讨论】:

        • 这似乎是从它的顶部中心而不是中心中心为圆设置动画。
        • 这是为了表明margin: 0 auto; 可以将其保持在原位,而不是作为最终解决方案。 OP 明确指定上边距,以便可以再次应用边距,并将其居中。
        • 你也应该在你的答案中包含它,否则你提供了一半的答案。
        • margin: 0 auto; 是这里需要的。 codepen 只是有点帮助。另一个 CSS 解决方案也不垂直居中。你为什么决定跳到这个问题上,只选择我的答案?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 2012-06-16
        • 2013-11-19
        相关资源
        最近更新 更多