[英]Getting the width of child element pure javascript
HTML:
<div class="project-box">
<img src="img/ifix.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of title</p>
</div>
</div>
javascipt的:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.clientWidth);
};
我正在嘗試使用純JavaScript獲取img寬度並最終獲得img高度我知道使用jQuery會更容易但我想只使用JavaScript來實現它。 編輯:我意識到我沒有為img和項目指定數組
工作的js:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
alert(img[0].offsetWidth);
};
getElementsByClassName
和getElementsByTagName
返回一個對象數組,因此您需要通過索引訪問實際元素,然后調用其方法/屬性
window.onload = function () {
var project = document.getElementsByClassName('project-box')[0];
var img = project.getElementsByTagName('img')[0];
alert(img.clientWidth);
};
演示: 小提琴
我相信project.getElementsByTagName('img'); 返回一個數組,即使它只有一個對象。
嘗試類似的東西
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
alert(img.pop().width); //This should remove the element from the array and then call width
};
試試這個:
alert(img.clientWidth);
這不起作用的原因是因為.getElementsByClassName()和.getElementsByTagName()都在[object HTMLContainer]中包裝元素,你需要從每個對象中選擇第一個元素。
這段代碼應該有效:
window.onload = function()
{
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
console.log(img[0].clientWidth);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.