![](/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.