Reading CSS value using JavaScript

前端 未结 7 691
梦毁少年i
梦毁少年i 2021-01-28 17:43

This works:

相关标签:
7条回答
  • 2021-01-28 18:06

    Try to put your css in the head section of the page.

    0 讨论(0)
  • 2021-01-28 18:12

    You cannot access CSS properties that way that have not been set using Javascript. You need to use getComputedStyle, see https://developer.mozilla.org/en/DOM/window.getComputedStyle On MSIE this works differently.

    0 讨论(0)
  • 2021-01-28 18:12

    Are you adverse to using jQuery?

    http://api.jquery.com/width/

    $(document).ready(function(){
        alert($("#hello").width());
    });
    
    0 讨论(0)
  • 2021-01-28 18:13

    jQuery will do it for you

    $('#hello').mouseover(function({
      alert($(this).width()); 
    });
    

    Just try it!

    0 讨论(0)
  • 2021-01-28 18:17

    Try the following

    window.onload = function(){
    
    var x = document.getElementById("hello");
    var y ="";
    if (x.currentStyle)
        y = x.currentStyle['width'];
    else if (window.getComputedStyle)
        y = document.defaultView.getComputedStyle(x,null).getPropertyValue('width');
    alert(y);
    
    
    
    };
    

    It was inspired from something I read Here

    0 讨论(0)
  • 2021-01-28 18:19

    I don't think style.width is given a value unless you explicitly define it one. As others have said you can use currentStyle/getComputedStyle to get actual values of CSS items.

    If you need JUST the width you can go with element.offsetWidth. If you need the value as a percent you'll have to compare the elements offsetWidth with the parents offsetWidth.

    0 讨论(0)
提交回复
热议问题