jQuery 是一个快速、简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。通过 jQuery,你可以方便地获取和操作 DOM 元素。
在使用 jQuery 获取图片的高宽时,有时会发现图片的高宽为 0。这通常是因为在图片完全加载之前尝试获取其尺寸。
load
事件确保在图片完全加载后再获取其尺寸:
$('img').on('load', function() {
var width = $(this).width();
var height = $(this).height();
console.log('Width: ' + width + ', Height: ' + height);
});
complete
属性检查图片是否已经加载完成:
$('img').each(function() {
if (this.complete) {
var width = $(this).width();
var height = $(this).height();
console.log('Width: ' + width + ', Height: ' + height);
} else {
$(this).on('load', function() {
var width = $(this).width();
var height = $(this).height();
console.log('Width: ' + width + ', Height: ' + height);
});
}
});
检查图片路径是否正确,确保图片能够正常加载。
确保没有 CSS 样式影响图片的显示尺寸。例如,检查是否有 width
和 height
属性设置为 0。
在处理图片上传、缩放、裁剪等场景时,需要获取图片的实际尺寸。确保在这些操作之前图片已经完全加载。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Image Dimensions</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<img id="myImage" src="path/to/your/image.jpg" alt="Sample Image">
<script>
$(document).ready(function() {
$('#myImage').on('load', function() {
var width = $(this).width();
var height = $(this).height();
console.log('Width: ' + width + ', Height: ' + height);
});
});
</script>
</body>
</html>
通过上述方法,你可以确保在图片完全加载后再获取其尺寸,避免获取到 0 的情况。