我有一段简单的代码:
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);
它返回这个错误信息:
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
我不知道我在这里做错了什么。谁能帮忙?
最佳答案
错误消息准确地告诉您出了什么问题:recipes
不是一个元素(它是一个元素集合)。
如果您想要与第一个 食谱元素关联的样式,请添加[0]
:
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes[0], null);
// Here ------------------------------------------^
...使用 querySelector
,它将只返回匹配给定 CSS 选择器的第一个元素:
var recipe = document.querySelector(".recipes");
var recipesStyle = window.getComputedStyle(recipe, null);
或者,如果您想处理每个 食谱元素的样式,您可以使用循环:
var recipes = document.getElementsByClassName("recipes");
for (var n = 0; n < recipies.length; ++n) {
var thisRecipesStyle = window.getComputedStyle(recipes[n], null);
// ...
}
关于javascript - getComputedStyle 执行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35393703/