CSS使父div不适合儿童大小

时间:2018-06-12 15:55:47

标签: javascript css

我有以下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 个答案:

答案 0 :(得分:0)

似乎工作正常。你能提供一个解释问题的小提琴吗?

Obs。:请注意,只要您第一次运行它,画布就会有一个固定的大小,并且只有在调整浏览器大小后才会调整大小。为了使其始终适合父母,您还需要在RefreshCanvasSize()上致电$(document).ready(...)

(我会将此添加为评论,但这样我可以提供代码示例的代码段)

&#13;
&#13;
$(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'))
}
&#13;
canvas {
  background: red;
}
.AnimationParent {
  background: blue;
  width: 100%;
  overflow:hidden;
}
&#13;
<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>
&#13;
&#13;
&#13;