在JavaScript中,处理图片的高宽通常涉及到HTML5的<img>
元素以及JavaScript的DOM操作。以下是一些基础概念和相关操作:
<img>
元素对应的DOM对象是HTMLImageElement
,它包含了图片的各种属性,如width
、height
、naturalWidth
、naturalHeight
等。var img = new Image();
img.onload = function() {
console.log('Natural dimensions: ' + this.naturalWidth + ' x ' + this.naturalHeight);
console.log('Current dimensions: ' + this.width + ' x ' + this.height);
};
img.src = 'path/to/image.jpg';
var img = document.getElementById('myImage');
img.width = 300; // 设置显示宽度为300像素
img.height = 200; // 设置显示高度为200像素
onload
事件确保图片加载完成后再获取尺寸。object-fit
属性来保持图片比例。以下是一个完整的示例,展示如何在图片加载完成后获取并设置其尺寸:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Dimensions</title>
</head>
<body>
<img id="myImage" src="path/to/image.jpg" alt="Sample Image">
<script>
var img = document.getElementById('myImage');
img.onload = function() {
console.log('Natural dimensions: ' + this.naturalWidth + ' x ' + this.naturalHeight);
console.log('Current dimensions: ' + this.width + ' x ' + this.height);
// 设置新的显示尺寸
this.width = 300;
this.height = 200;
};
</script>
</body>
</html>
通过上述代码,你可以在控制台中看到图片的原始尺寸和设置后的显示尺寸。
领取专属 10元无门槛券
手把手带您无忧上云