在网页开发中,innerWidth
和 innerHeight
是两个常用的属性,它们分别表示浏览器窗口的内部宽度和高度,不包括浏览器的工具栏、滚动条等。这些属性通常用于响应式设计,以便根据窗口大小调整页面布局。
这些属性常用于:
以下是一个简单的示例,展示如何使用 innerWidth
和 innerHeight
在页面边框周围绘制图像:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw Image Around Border</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
}
#canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawImage();
}
function drawImage() {
const img = new Image();
img.src = 'path/to/your/image.jpg'; // 替换为你的图像路径
img.onload = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const borderWidth = 10; // 边框宽度
ctx.drawImage(img, borderWidth, borderWidth, canvas.width - 2 * borderWidth, canvas.height - 2 * borderWidth);
};
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas(); // 初始化画布
</script>
</body>
</html>
canvas
元素用于绘图。canvas
全屏显示,并移除默认的边距和填充。resizeCanvas
函数调整 canvas
的大小以匹配窗口的内部尺寸。drawImage
函数加载图像并在 canvas
上绘制,留出一定的边框宽度。resize
事件,以便在窗口大小变化时重新绘制图像。img.onload
事件中执行绘制操作。resize
事件的处理。通过这种方式,你可以确保图像始终适应窗口大小,并在页面边框周围正确显示。
领取专属 10元无门槛券
手把手带您无忧上云