[英]I want to get the font-size using window.getComputedStyle() in javascript but it can't
var menu = document.getElementsByClassName("menu"); var a = window.getComputedStyle(menu, null).fontSize(); var fontSize = parseFloat(a); alert("HELLO");
那是代碼。 所以我想得到一個名為menu的類的字體大小。 然后,我想提醒(“你好”)。 但是,警報不會運行,當我將警報更改為警報(fontSize)時,它也無法運行。 我的代碼有什么問題嗎?
您應該將元素傳遞給.getComputedStyle
方法。 .getElementsByClassName
返回一個集合。 您需要從集合中選擇第一個元素,或使用.querySelector
選擇目標元素。 另請注意, .getComputedStyle
返回的對象沒有fontSize
方法,它是一個屬性。 您還可以使用.getPropertyValue
獲取特定值:
// 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.computedStyleMap();
樣式將給出具有所有樣式的對象。 只需打印並檢查是否得到它。
你的代碼有幾個問題。
首先, getComputedStyle
期望它的第一個參數是一個DOM元素。 getElementsByClassName
返回一個HTMLCollection
,一個類似於數組的對象,包含DOM元素的實時集合 。 這就是為什么,如果你查看你的錯誤控制台,你應該看到一條錯誤消息“TypeError:Window.getComputedStyle的參數1沒有實現接口元素。”。
其次, getComputedStyle
返回一個CSSStyleDeclaration
對象,該對象沒有.fontSize
方法。 但它有一個getPropertyValue
方法,您可以使用它來獲取字體大小。
// 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.