代码之家  ›  专栏  ›  技术社区  ›  Thomas Carlton

css使父div不适合子级大小

  •  0
  • Thomas Carlton  · 技术社区  · 8 年前

    我有以下HTML:

       <div class="AnimationParent">                               
        <canvas id="canvas" width="534" height="554"></canvas>
      </div>
    

    我正在使用javascript设置画布项的大小,以避免在动画中出现缩放问题…:

       $(window).resize(function() {
                    RefreshCanvasSize();                                                        
                    SetLayout();
                });               
    
       function RefreshCanvasSize() {
                var ParentWidth, ParentHeight;
    
                ParentWidth = $(".AnimationParent").width();
                ParentHeight = $(".AnimationParent").height();
    
                $("#canvas").prop('width', ParentWidth);
                $("#canvas").prop('height', ParentHeight);                                      
       }
    

    下面的代码在我展开一个页面时有效,但在它收缩时无效。父div(animationparent)不会收缩。

    下面是animationparent的css:

     width:100%;
     overflow:hidden;
    

    有人能帮忙吗?

    当做,

    1 回复  |  直到 8 年前
        1
  •  0
  •   Dinei Ahmad Yones    8 年前

    似乎工作得很好。你能提供一把小提琴来解释这个问题吗?

    obs.:请注意,第一次运行时,画布的大小是固定的,只有在调整浏览器的大小后才会调整大小。为了让它永远适合父母,你需要打电话给 RefreshCanvasSize() $(document).ready(...) 也。

    (我将此添加为注释,但这样我可以提供代码示例的片段)

    $(window).resize(function() {
      RefreshCanvasSize();                                                        
      //SetLayout();
    });               
    
    function RefreshCanvasSize() {
      var ParentWidth, ParentHeight;
    
      ParentWidth = $(".AnimationParent").width();
      ParentHeight = $(".AnimationParent").height();
    
      $("#canvas").prop('width', ParentWidth);
      $("#canvas").prop('height', ParentHeight);
      console.log($("#canvas").prop('width'), $("#canvas").prop('height'))
    }
    canvas {
      background: red;
    }
    .AnimationParent {
      background: blue;
      width: 100%;
      overflow:hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="AnimationParent">                               
      <canvas id="canvas" width="534" height="554"></canvas>
    </div>