我有一个简单的代码:
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);它返回以下错误消息:
Uncaught :未能在“窗口”上执行“getComputedStyle”:参数1不是“元素”类型。
我不知道我在这里做错了什么。有人能帮忙吗?
发布于 2016-02-14 15:54:27
错误消息告诉您到底出了什么问题:recipes不是一个元素(它是一个元素集合)。
如果您想要与第一个食谱元素关联的样式,可以添加[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);
// ...
}https://stackoverflow.com/questions/35393703
复制相似问题