Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript getComputedStyle未能执行_Javascript_Getcomputedstyle - Fatal编程技术网

Javascript getComputedStyle未能执行

Javascript getComputedStyle未能执行,javascript,getcomputedstyle,Javascript,Getcomputedstyle,我有一段简单的代码: var recipes = document.getElementsByClassName("recipes"); var recipesStyle = window.getComputedStyle(recipes, null); 它返回以下错误消息: 未捕获类型错误:未能在“窗口”上执行“getComputedStyle”: 参数1不是“元素”类型 我不知道我做错了什么。有人能帮忙吗?错误消息会准确地告诉您出了什么问题:recipes不是元素(它是元素的集合) 如果想

我有一段简单的代码:

var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);
它返回以下错误消息:

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


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

错误消息会准确地告诉您出了什么问题:
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);
    // ...
}
var recipes=document.getElementsByClassName(“recipes”);
对于(变量n=0;n
Use
var recipesStyle=window.getComputedStyle(recipes[0],null)document.getElementById('yourElementId')对我有效,而不是使用document.getElementsByClassName