2

我有这个简单的代码:

var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);

它返回此错误消息:

未捕获的类型错误:无法在“窗口”上执行“getComputedStyle”:参数 1 不是“元素”类型。

我不知道我在这里做错了什么。任何人都可以帮忙吗?

4

1 回答 1

5

错误消息准确地告诉您出了什么问题:recipesis not an element (it's a collection of elements )。

如果您想要与第一个配方元素关联的样式,请添加[0]

var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes[0], null);
// Here ------------------------------------------^

...use 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);
    // ...
}
于 2016-02-14T15:54:27.527 回答