是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
让我们将在这里学到的所有内容组合成一个简单的函数(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>
其他回答
此外(除了Rex和Ian的回答)还有:
imageElement.naturalHeight
and
imageElement.naturalWidth
它们提供了图像文件本身的高度和宽度(而不仅仅是图像元素)。
clientWidth和clienttheight是DOM属性,显示DOM元素内部维度的当前浏览器大小(不包括边距和边框)。在IMG元素的情况下,这将得到可见图像的实际尺寸。
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
Try
函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小
这是我的方法:
var imgSrc, imgW, imgH;
function myFunction(image) {
var img = new Image();
img.src = image;
img.onload = function() {
return {
src: image,
width: this.width,
height: this.height};
}
return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
// Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load', function() {
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
x.addEventListener('load', function() {
console.log(imgW + 'x' + imgH); // 276x110
});
console.log(imgW); // undefined.
console.log(imgH); // undefined.
console.log(imgSrc); // undefined.
其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。
由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。
推荐文章
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何减去日期/时间在JavaScript?
- 如何检测“搜索”HTML5输入的清除?
- 字符串中的单词大写
- 返回一个正则表达式匹配()在Javascript的位置?
- 当元素从DOM中移除时触发事件
- Ajax成功事件不工作
- 为什么JavaScript中弃用arguments.callee.caller属性?
- 在typescript中一直使用。tsx而不是。ts有什么缺点吗?
- 如何在Angular.js中配置不同的环境?
- 引导下拉与Hover