admin管理员组文章数量:1435859
var menu = document.getElementsByClassName("menu");
var a = window.getComputedStyle(menu, null).fontSize();
var fontSize = parseFloat(a);
alert("HELLO");
var menu = document.getElementsByClassName("menu");
var a = window.getComputedStyle(menu, null).fontSize();
var fontSize = parseFloat(a);
alert("HELLO");
That is the code. So I want to get the font-size of a class named menu. Then, I want to alert("HELLO"). But, the alert won't run and when I change the alert into alert(fontSize), it is not working either. Is anything wrong with my code?
Share Improve this question asked Oct 7, 2018 at 14:24 Armand DwiArmand Dwi 1371 silver badge5 bronze badges 1- Have a look at:w3schools./jsref/… – Prashant Pimpale Commented Oct 7, 2018 at 14:26
3 Answers
Reset to default 4You should pass an element to .getComputedStyle
method. .getElementsByClassName
returns a collection. You either need to select the first element from the set or use .querySelector
for selecting the target element. Also note that returned object by .getComputedStyle
doesn't have fontSize
method, it's a property. You can also use the .getPropertyValue
for getting a specific value:
// select the first .menu element
var menu = document.querySelector(".menu");
var a = window.getComputedStyle(menu, null).getPropertyValue('font-size');
var menu = document.querySelector(".menu");
var styles = menu.putedStyleMap();
styles will give the object which has all the styles available in it. Just print it and check if you got it.
There are a couple of things wrong with your code.
First, getComputedStyle
expects its first argument to be a single DOM element.
getElementsByClassName
returns a
HTMLCollection
,
an array-like object containing a live
collection of DOM elements. That
is why, if you look in your error console, you should see an error message along
the lines of "TypeError: Argument 1 of Window.getComputedStyle does not
implement interface Element.".
Second, getComputedStyle
returns a
CSSStyleDeclaration
object, which does not have a .fontSize
method. It does however have a
getPropertyValue
method that you can use to get the font size.
// use querySelector, which returns a single DOM element that is the first in
// the DOM to match the provided query string
let menu = document.querySelector(".menu");
// You can just omit the second parameter if you are not targeting a pseudo
// element.
let styles = window.getComputedStyle(menu);
// get the font size in px
let fontSize = styles.getPropertyValue('font-size');
fontSize = parseFloat(fontSize);
alert('font-size =' + fontSize);
.menu {
font-size: 1.5em;
}
<div class="menu">Menu</div>
版权声明:本文标题:html - I want to get the font-size using window.getComputedStyle() in javascript but it can't - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745666122a2669299.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论