![](/img/trans.png)
[英]How can I get information about images in a stylesheet using JavaScript
[英]How can I get the size of images by javascript?
我试图通过javascript获取图像大小,因为我使用了offsetHeight,scrollHeight,clientHeight,但这些都不起作用。 naturalHeight属性可以工作,但是即使使用css调整了图像的大小,它也会返回图像的实际大小。 奇怪的是,如果我单击“尝试”按钮,则相同的代码将运行良好。 我在哪里错了?
请解释:
var imageHeightMethodOne = document.querySelector('.one').offsetHeight; console.log('MT1-The height of img is ' + imageHeightMethodOne); var imageHeightMethodTwo = document.querySelector('.one').scrollHeight; console.log('MT2-The height of img is ' + imageHeightMethodTwo); var imageHeightMethodThree = document.querySelector('.one').clientHeight; console.log('MT3-The height of img is ' + imageHeightMethodThree); var imageHeightMethodFour = document.querySelector('.one').naturalHeight; console.log('MT4-The height of img is ' + imageHeightMethodFour); function test() { var imageHeightMethodOne = document.querySelector('.one').offsetHeight; console.log('MT1-The height of img is ' + imageHeightMethodOne); var imageHeightMethodTwo = document.querySelector('.one').scrollHeight; console.log('MT2-The height of img is ' + imageHeightMethodTwo); var imageHeightMethodThree = document.querySelector('.one').clientHeight; console.log('MT3-The height of img is ' + imageHeightMethodThree); var imageHeightMethodFour = document.querySelector('.one').naturalHeight; console.log('MT4-The height of img is ' + imageHeightMethodFour); }
<div class='container' style='width:40%;'> <img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' /> </div> <button onclick='test()'>try</button>
function test() { var imageHeightMethodOne = document.querySelector('.one').offsetHeight; console.log('MT1-The height of img is ' + imageHeightMethodOne); var imageHeightMethodTwo = document.querySelector('.one').scrollHeight; console.log('MT2-The height of img is ' + imageHeightMethodTwo); var imageHeightMethodThree = document.querySelector('.one').clientHeight; console.log('MT3-The height of img is ' + imageHeightMethodThree); var imageHeightMethodFour = document.querySelector('.one').naturalHeight; console.log('MT4-The height of img is ' + imageHeightMethodFour); }
<body onload="test();"> <div class='container' style='width:40%;'> <img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' /> </div> <button onclick='test()'>try</button> </body>
在onLoad事件中调用该函数。 这将确保页面的资产已加载,包括图像,css。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.