我有以下 HTML:
<div class="AnimationParent">
<canvas id="canvas" width="534" height="554"></canvas>
</div>
我正在使用 javascript 设置 Canvas 元素的大小,以避免我的动画中出现比例问题...:
$(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;
谁能帮忙吗?
问候,
最佳答案
似乎工作正常。你能提供一个解释问题的 fiddle 吗?
观察:请注意,一旦您第一次运行它, Canvas 的大小就会固定,并且只会在调整浏览器大小时调整大小。要使其始终适合父级,您还需要在 $(document).ready(...)
上调用 RefreshCanvasSize()
。
(我会将其添加为评论,但这样我就可以提供带有代码示例的片段)
$(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>
关于javascript - CSS使父div不适合 child 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821329/