我正在尝试创建一个具有网格布局的页面,当我尝试将较小的画布放入网格的 div 之一时,我遇到了一些问题。主要问题是我无法获取父 div 的高度,这是第一步。
这就是代码示例,我尝试了一些方法,但高度返回为未定义。另外,有没有更好的方法来实现这种布局?如果有什么错误的话,非常抱歉。
.all-grid{
width:80%; /*I've also tried switching these to px*/
height: 100%;
display:grid;
grid-template-columns: 50% 5% 15% 30%;
grid-template-rows: 5% 15% 40% 10% 25% 5%;}
.header{
grid-row: 1/2;
grid-column: 1/5;}
.yellow{
background-color: yellow;
grid-row: 2/3;
grid-column: 1/2;}
.orange{
background-color: orange;
grid-row: 4/5;
grid-column: 1/3;}
let canvas;
let ctx;
const start=()=>{
...
canvas.width = $(".header").width(); /*undefined, tried using document.querySelector(".header") as well*/
canvas.height = $(".header").height(); /*undefined*/
<div class="header">
<canvas></canvas>
</div>
...
您可能想对
canvas
元素使用 JQuery 选择器,如下所示:
canvas = $('canvas').get(0);
演示:
let canvas;
let ctx;
const start = () => {
//...
console.log($(".header").width());
canvas = $('canvas').get(0);
canvas.width = $(".header").width();
console.log(canvas.width);
canvas.height = $(".header").height();
console.log(canvas.height);
}
start();
canvas {
border: 1px solid blue;
}
.all-grid {
width: 80%;
/*I've also tried switching these to px*/
height: 100%;
display: grid;
grid-template-columns: 50% 5% 15% 30%;
grid-template-rows: 5% 15% 40% 10% 25% 5%;
}
.header {
grid-row: 1/2;
grid-column: 1/5;
}
.yellow {
background-color: yellow;
grid-row: 2/3;
grid-column: 1/2;
}
.orange {
background-color: orange;
grid-row: 4/5;
grid-column: 1/3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
<canvas></canvas>
</div>