【问题标题】:Getting width of an element defined in CSS in em在 em 中获取 CSS 中定义的元素的宽度
【发布时间】:2012-09-13 12:49:21
【问题描述】:

我无法获取在 CSS 中定义的元素的宽度。我想出了如何使用 Javascript 获取 CSS 规则,但我无法访问宽度。 Menu 是我在 CSS 中使用 em 定义的固定宽度。

我正在尝试根据浏览器窗口减去固定的菜单宽度来更改div1的宽度。

注意:我已经尝试过使用style.width,但它会在控制台中返回一个空行。

jsfiddle:http://jsfiddle.net/kj6pQ/

var div1 = document.createElement('div'), 
css = getMatchedCSSRules(document.getElementById('menu'));

console.log(css); //works but dont' konw how to access width

div1.style.width = window.innerWidth - <!-- menu width -->;

【问题讨论】:

    标签: javascript css styles width


    【解决方案1】:

    试试这个方法:

    var width = window.getComputedStyle(document.getElementById("menu"), null).getPropertyValue("width");
    

    【讨论】:

      【解决方案2】:

      使用getComputedStyle:

      var css = document.getElementById('menu');
      
      console.log(window.getComputedStyle(css).width);​
      

      http://jsfiddle.net/kj6pQ/6/

      【讨论】:

        【解决方案3】:

        使用“offsetWidth”访问菜单的宽度

        var div1 = document.createElement('div'), 
        css = document.getElementById('menu').offsetWidth;
        
        console.log(css);
        div1.style.width = css + "px";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-30
          • 2012-04-01
          • 2020-03-03
          相关资源
          最近更新 更多