javascript 在 em 中获取 CSS 中定义的元素的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12524736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:26:05  来源:igfitidea点击:

Getting width of an element defined in CSS in em

javascriptcssstyleswidth

提问by Krishna Kumar

I am having trouble getting the width of an element defined in CSS. I figured out how to get the CSS rules using Javascript, but I can't access the width. Menuis fixed width that I defined in CSS using em.

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

I am trying to change the width of the div1based on the browser window minus the fixed menu width.

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

Note: I already tried using style.width, but it returns a blank line in the console.

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

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

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 -->;

回答by Krishna Kumar

use 'offsetWidth' to access the menu's width

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

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

console.log(css);
div1.style.width = css + "px";

回答by Ana

Use getComputedStyle:

使用getComputedStyle

var css = document.getElementById('menu');

console.log(window.getComputedStyle(css).width);?

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

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

回答by dfsq

Try this way:

试试这个方法:

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