我有一个简单的 HTML canvas
,它覆盖了整个页面,它本身显示得很好。
const canvas = document.getElementById("mainCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize",
function() {
canvas.width = innerWidth;
canvas.height = innerHeight;
}
);
body {
background-color: red;
margin: 0;
padding: 0;
}
#mainCanvas {
display: block;
background-color: blue;
}
<canvas id = "mainCanvas"></canvas>
但是,当我尝试在其下方添加 div
元素时,即使所有元素都小于总宽度(并且因此不应该有任何水平溢出)。例如:
const canvas = document.getElementById("mainCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize",
function() {
canvas.width = innerWidth;
canvas.height = innerHeight;
}
);
body {
background-color: red;
margin: 0;
padding: 0;
}
#mainCanvas {
display: block;
background-color: blue;
}
#info {
width: 50px;
height: 50px;
background-color: green;
}
<canvas id = "mainCanvas"></canvas>
<div id = "info"></div>
我知道我可以使用 overflow-x:hidden
解决水平滚动条显示的问题,但我想了解为什么它首先出现。
最佳答案
这与 <canvas>
无关并且其行为与任何其他 block 元素相同,例如 <div>
.
如果您在<body>
中设置了单独的元素的尺寸为innerWidth
/innerHeight
和家长 <body>
没有内边距或边距,那么您就已经用完了页面上的所有空间,并且不需要滚动条。
如果添加 <div>
在全页元素下方,需要一个垂直滚动条以允许用户向下移动视口(viewport)来查看它。但这个新的垂直滚动条现在占用了一些被 innerWidth
忽略的水平空间。 ,如 docs state :
innerWidth
returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.
原始元素正好设置为 innerWidth
像素现在水平溢出屏幕垂直滚动条的宽度。因此,水平滚动条就变得必要了。
您可以尝试的一个选项是 document.documentElement.clientWidth
。作为docs state :
clientWidth
[...] includes padding but excludes borders, margins, and vertical scrollbars (if present).
(运行代码片段后您可能需要单击“完整页面”才能看到差异):
const canvas = document.getElementById("main-canvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
window.addEventListener("resize", // TODO debounce
function () {
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
}
);
body {
background-color: red;
margin: 0;
padding: 0;
}
#main-canvas {
display: block;
background-color: blue;
}
#info {
width: 50px;
height: 50px;
background-color: green;
}
<canvas id="main-canvas"></canvas>
<div id="info"></div>
关于html - 为什么在 HTML Canvas 下添加小 div 时会出现水平滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70058848/