![](/img/trans.png)
[英]How do I center a div in the middle of the page using jQuery and keep it centered when window is re-sized?
[英]How do I keep an element that fills the window centered?
这就是你想要的吗?
这是代码的重构版本,可根据窗口调整大小将画布调整为窗口的最小尺寸(宽度或高度)。 它还将画布的display
设置为block
并使用margin: 0 auto
将其居中。
这是演示 。
更新1我已经用注释进行重构,以显示在何处更改代码以将画布的大小调整为窗口高度和宽度之间的最大尺寸。
更新2我已经重构为适合画布,因此通过将宽度和高度设置为确切的窗口,十字准线始终居中。
我还更新了CSS,以删除所有填充和边距。
画布在window.onresize
上重绘。
var canvas = document.createElement('canvas'); document.body.appendChild(canvas); function setSize() { var w = window.innerWidth; var h = window.innerHeight; //var size = (h > w) ? h : w; //<<<< resize to largest between height and width //var size = (h < w) ? h : w; //<<<< resize to smallest between height and width //canvas.width = size; //canvas.height = size; canvas.width = w; //<<<< exact resizing to width canvas.height = h; //<<<< exact resizing to height } function draw() { var context = canvas.getContext('2d'); context.fillRect(0, 0, canvas.width, canvas.height); context.strokeStyle = 'red'; context.moveTo(canvas.width/2, 0); context.lineTo(canvas.width/2, canvas.height); context.moveTo(0, canvas.height/2); context.lineTo(canvas.width, canvas.height/2); context.stroke(); } setSize(); draw(); window.onresize = function(e) { setSize(); draw(); };
* { padding: 0; margin: 0; } canvas { display: block; margin: 0 auto; }
您可以做类似canvas {的操作:position:fixed; 顶部:-500px; }
要使用页面调整画布的大小,请尝试添加窗口调整大小的侦听器:
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.width = window.innerHeight;
});
如果要删除边距,以使画布填充整个页面,请尝试在页面上添加以下CSS:
body {
margin: 0 !important;
padding: 0 !important;
}
经过多番摆弄之后,我想我明白了。 这是有效的演示 ( 全屏版本 )。 我最终使用了以下循环:
function render() {
requestAnimationFrame(render);
window.scrollTo(
document.documentElement.scrollWidth/2 - window.innerWidth/2,
document.documentElement.scrollHeight/2 - window.innerHeight/2
);
}
requestAnimationFrame(render);
会自动将窗口滚动到整个可滚动区域(包括不可见部分)的中间位置,减去可见区域本身大小的一半。
感谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.