javascript - getComputedStyle 执行失败

标签 javascript getcomputedstyle

我有一段简单的代码:

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/

相关文章:

javascript - 为什么eslint不检查JS?

javascript - UIWebView和javascript需要加载数据

javascript - bytes32 到 javascript 中的字符串

dart - 通过dart中的getComputedStyle访问伪元素属性值

javascript - 如何断言 HTML 元素在包含样式表后不会改变其外观?

javascript - 如何在 swiperjs ReactJS 中将初始事件幻灯片设置为不同索引?

javascript - 如何阻止 child 继承 parent 的不透明度

javascript - 将 getComputedStyle 与边框框一起使用应返回无边框和填充的高度

javascript - 如何正确更新对象?

javascript - 如何在 Javascript 中使用 ComputedStyle 获取边框宽度?