Jquery windows.width(height) 溢出

标签 jquery html css

我对窗口大小有疑问。我正在像这样测量窗口的大小

var boxwidth = $(window).width();
var boxheight = $(window).height();

然后创建一个canvas

var canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = boxwidth;
    this.canvas.height = boxheight;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[0]);
  }

但是我的宽度和高度都溢出了。

我想创建完全适合窗口大小的 Canvas 。现在,我有很多溢出

image

我已经在 body 中添加了 margin:0padding:0

最佳答案

嗯,我试图找到一个“正常”的解决方案,但我没有找到,所以这里有一个“棘手”的解决方案。这是一个想法,但我认为您需要对其进行自定义以使其适合您的元素。

逻辑是创建一个 div,它将获取文档的完整宽度和高度,并根据它设置 Canvas 尺寸。最后一步是恢复元素的状态(html、body 等)

所以:

$('html, body').css({position: 'relative', height: '100%', overflow:'hidden'});
var tester = $('<div style="width:100%;height:100%" />').appendTo(document.body);
$('canvas').css({
  width:$('body').width(),
  height:tester.height()
});
tester.remove();
$('html, body').removeAttr('style');
html, body {
  margin:0;  
}

canvas {
  background:red;
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas></canvas>

http://jsbin.com/pinide/edit?html,css,js

关于Jquery windows.width(height) 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094543/

相关文章:

Javascript/Jquery 检查 id 是否已经存在

javascript - 使用 Date.js 以月份名称、##、#### 格式预填充日期

html - 如何使用 HTML CSS 将图章(cachet)添加到报价中

javascript - 如何在 Javascript/HTML5 中解析 Excel (XLS) 文件

JQuery 向下/向上滑动 - 仅显示来自同一类名称的一个 div

javascript - MVC - 使用 Jquery 在部分 View 之间传递 ViewModel

javascript - 应该在 jQuery 文档内部或外部编写和调用 Javascript 函数吗?

javascript - SVG 路径和图像

css - 容器的绝对和相对定位

javascript - 使用 javascript 计时器更改 Div 的不透明度