首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getComputedStyle未能执行

getComputedStyle未能执行
EN

Stack Overflow用户
提问于 2016-02-14 15:52:15
回答 1查看 14.7K关注 0票数 3

我有一个简单的代码:

代码语言:javascript
复制
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);

它返回以下错误消息:

Uncaught :未能在“窗口”上执行“getComputedStyle”:参数1不是“元素”类型。

我不知道我在这里做错了什么。有人能帮忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-14 15:54:27

错误消息告诉您到底出了什么问题:recipes不是一个元素(它是一个元素集合)。

如果您想要与第一个食谱元素关联的样式,可以添加[0]

代码语言:javascript
复制
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes[0], null);
// Here ------------------------------------------^

...use querySelector,它只返回匹配给定CSS选择器的第一个元素:

代码语言:javascript
复制
var recipe = document.querySelector(".recipes");
var recipesStyle = window.getComputedStyle(recipe, null);

或者,如果您想处理每个菜谱元素的样式,可以使用一个循环:

代码语言:javascript
复制
var recipes = document.getElementsByClassName("recipes");
for (var n = 0; n < recipies.length; ++n) {
    var thisRecipesStyle = window.getComputedStyle(recipes[n], null);
    // ...
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35393703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档