是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:
$(document).ready(function(){
var width = img.clientWidth;
var height = img.clientHeight;
});
其他回答
其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。
由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。
我对jQuery的看法
免责声明:这并不一定能回答这个问题,但可以拓宽我们的能力。它在jQuery 3.3.1中进行了测试
让我们考虑一下:
你有图像的URL/路径,你想要得到图像的宽度和高度,而不是在DOM上渲染它, 在DOM上呈现图像之前,您需要将offsetParent节点或图像div包装器元素设置为图像的宽度和高度,以便为不同的图像大小创建一个流体包装器,即,当单击按钮以查看模式/灯箱上的图像时
我要这样做:
// image path
const imageUrl = '/path/to/your/image.jpg'
// Create dummy image to get real width and height
$('<img alt="" src="">').attr("src", imageUrl).on('load', function(){
const realWidth = this.width;
const realHeight = this.height;
alert(`Original width: ${realWidth}, Original height: ${realHeight}`);
})
在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。
$("ImageID").load(function(){
console.log($(this).width() + "x" + $(this).height())
})
让我们将在这里学到的所有内容组合成一个简单的函数(imageDimensions())。它使用承诺。
// helper to get dimensions of an image const imageDimensions = file => new Promise((resolve, reject) => { const img = new Image() // the following handler will fire after a successful loading of the image img.onload = () => { const { naturalWidth: width, naturalHeight: height } = img resolve({ width, height }) } // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one) img.onerror = () => { reject('There was some problem with the image.') } img.src = URL.createObjectURL(file) }) // here's how to use the helper const getInfo = async ({ target: { files } }) => { const [file] = files try { const dimensions = await imageDimensions(file) console.info(dimensions) } catch(error) { console.error(error) } } <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script> Select an image: <input type="file" onchange="getInfo(event)" /> <br /> <small>It works offline.</small>
在获取元素的属性之前,文档页面应该是onload的:
window.onload = function(){
console.log(img.offsetWidth,img.offsetHeight);
}
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 如何在JSON中使用杰克逊更改字段名
- 很好的初学者教程socket.io?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置