将元素高度设置为clientHeight导致页面滚动

我有这段代码:


<!DOCTYPE html>

<html>

  <head>

    <script>      

        window.addEventListener('load', () => {

            document.getElementById("c").width = document.documentElement.clientWidth;

            document.getElementById("c").height = document.documentElement.clientHeight;

        })

    </script>

  </head>

  <body style="margin: 0;">

    <canvas id="c" style="background-color: red;"></canvas>

  </body>

</html>

为什么它会生成比浏览器视口更大的画布,并制作滚动条?除此之外,它在画布下方留出了一些空白。为什么以及如何解决?谢谢!


呼唤远方
浏览 118回答 1
1回答

神不在的星期二

默认情况下,画布显示设置为display: inline;您只需将画布显示设置为display: block;<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; window.addEventListener('load', () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("c").width = document.documentElement.clientWidth;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("c").height = document.documentElement.clientHeight;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; </script>&nbsp; </head>&nbsp; <body style="margin: 0;">&nbsp; &nbsp; <canvas id="c" style="background-color: red; display: block;"></canvas>&nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript