最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

css - Javascript - simply get height of an element - Stack Overflow

programmeradmin5浏览0评论

I know this properbly is a duplicate, but i cant get it right from some of the other answers! Really hope you can help!

I simply want to get the width of an element, and then assign it to the height of the same element.

But i cant seem to get the width passed... And I really dont know why - just gets and "undefined".

Read something about the js asking for the width before the elements are added to the DOM, but no matter where I place my "onload", og place the js script, it doesnt seem to make any difference, and i still can add static height to the same element, but just cant get the width! Thanks!

var width_ele = document.getElementsByClassName("image");
var width = width_ele[0].style.offsetWidth;

alert(width);

var ele = document.getElementsByClassName("image");
for (var i = 0; i < ele.length; i++) {
ele[i].style.height = 100 + "px"; // here I wanted the "100" to be the variable "width"...
}

/

I know this properbly is a duplicate, but i cant get it right from some of the other answers! Really hope you can help!

I simply want to get the width of an element, and then assign it to the height of the same element.

But i cant seem to get the width passed... And I really dont know why - just gets and "undefined".

Read something about the js asking for the width before the elements are added to the DOM, but no matter where I place my "onload", og place the js script, it doesnt seem to make any difference, and i still can add static height to the same element, but just cant get the width! Thanks!

var width_ele = document.getElementsByClassName("image");
var width = width_ele[0].style.offsetWidth;

alert(width);

var ele = document.getElementsByClassName("image");
for (var i = 0; i < ele.length; i++) {
ele[i].style.height = 100 + "px"; // here I wanted the "100" to be the variable "width"...
}

http://jsfiddle/qL0hj4jc/10/

Share Improve this question edited Jun 15, 2015 at 16:25 Ziltoid asked Jun 11, 2015 at 20:59 ZiltoidZiltoid 351 silver badge6 bronze badges 1
  • 1 Share your code please. – Nikhil Aggarwal Commented Jun 11, 2015 at 21:00
Add a ment  | 

2 Answers 2

Reset to default 4
var width = width_ele[0].offsetHeight; // did you mean offsetWidth?

offsetHeight/offsetWidth is a property of the element itself, not its style table.

I have updated your code.

You need to use

var width = width_ele[0].offsetWidth;

Here is the updated fiddle - http://jsfiddle/qL0hj4jc/4/

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

发布评论

评论列表(0)

  1. 暂无评论