首先我將解釋我目前爲止的內容; 動態畫布總是在頁面中間,它的寬度是通過javascript計算來計算的,所以它可能會有所不同,之後一些flexbox div被添加到它的兩側,並且它們平均填充頁面的其餘部分(它的作用相同這樣即使CTRL調整大小):在舊版瀏覽器中顯示flexbox
https://jsfiddle.net/62g1mqw0/2/
<div class="wrapper">
<div class="divA"></div>
<div class="divB">
<canvas id="canvas"></canvas>
</div>
<div class="divC"></div>
</div>
<style type="text/css">
* {
box-sizing: border-box;
}
body {
height: 100vh;
margin: 0;
}
.wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
height: 100%;
}
.wrapper div {
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
border: 1px solid;
}
.wrapper .divB {
border: none;
}
#canvas {
vertical-align:top;
}
</style>
<script>
var canvas = document.getElementById("canvas");
var WIDTH = 500; // This could be anything! it comes from
//previous calculations which I did not include here because they are irelevant
document.getElementsByClassName('divB')[0].style.flex = '0 0 ' + WIDTH + 'px';
var width = document.getElementsByClassName('divB')[0].getBoundingClientRect().width;
var height = document.getElementsByClassName('divB')[0].getBoundingClientRect().height;
document.getElementById("canvas").style.width = width + 'px';
document.getElementById("canvas").style.height = height + 'px';
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, width, height);
// resize handler Ref: https://developer.mozilla.org/en-US/docs/Web/Events/resize
(function() {
window.addEventListener("resize", resizeThrottler, false);
var resizeTimeout;
function resizeThrottler() {
if (!resizeTimeout) {
resizeTimeout = setTimeout(function() {
resizeTimeout = null;
actualResizeHandler();
}, 66);
}
}
function actualResizeHandler() {
var width = document.getElementsByClassName('divB')[0].getBoundingClientRect().width;
var height = document.getElementsByClassName('divB')[0].getBoundingClientRect().height;
document.getElementById("canvas").style.width = width + 'px';
document.getElementById("canvas").style.height = height + 'px';
ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, width, height);
}
}());
</script>
正如你可以在的jsfiddle看到,總的結果是,寬度和頁面高度的100%是由兩個帆布和Flexbox的填補。
現在,在現代瀏覽器中,您不會看到問題,但在舊版瀏覽器中,您會看到奇怪的內容;一個div漂浮到下一個,一些黑點等。對於舊的瀏覽器來說,支持舊的瀏覽器對我來說非常重要,因爲我用舊版本的cordova和Android用戶進行編譯,他們可能會看到我的應用程序非常奇怪。我已經在KitKat和一些更舊的版本上測試過它,我不知道他們爲什麼不正確地支持Flexbox。我添加了-webkit行,但它仍然沒有幫助。我甚至不介意另一個完全不同的解決方案,不涉及flexbox
flexbox瀏覽器兼容性:http://stackoverflow.com/q/35137085/3597276 –