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

javascript - Using elements that are added to an array with (document.getElementById('ID')) - Stack Overflow

programmeradmin2浏览0评论

Why does this code not work?

var all_obj_element= new Array();
all_obj_element[0]= document.getElementById('Img3');            
alert(all_obj_element[0].style.width);

The alert shows an empty box!

Why does this code not work?

var all_obj_element= new Array();
all_obj_element[0]= document.getElementById('Img3');            
alert(all_obj_element[0].style.width);

The alert shows an empty box!

Share Improve this question edited Nov 22, 2012 at 18:10 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked May 26, 2011 at 6:19 hamze torabzadehamze torabzade 7,3316 gold badges35 silver badges43 bronze badges 1
  • Did you try .width instead of style.width ? – mplungjan Commented May 26, 2011 at 6:23
Add a ment  | 

3 Answers 3

Reset to default 6

Because you haven't set the width. Here is how you get the puted style value of an element:

var putedStyle = function (el,style) {
    var cs;
    if (typeof el.currentStyle != 'undefined'){
        cs = el.currentStyle;
    }
    else {
        cs = document.defaultView.getComputedStyle(el,null);
    }
    return  cs[style];
}

Now let's get the value:

var element = document.getElementById('Img3');

alert(putedStyle(element,'width'));

The element with the id Img3 has not had its .style.width property set (which can be done by assigning a value to it via JavaScript, or by using the style attribute).

Quirks Mode has an article on how to read the puted style in a cross-browser fashion.

If there is no need to see the STYLEd width, just look at the width:

var all_obj_element= [];
all_obj_element[0]= document.getElementById('Img3');            
alert(all_obj_element[0].width);
发布评论

评论列表(0)

  1. 暂无评论