您必须遍历 的结果document.getElementsByTagName("CODE")
,它是一个类似数组的变量。这是一个 jQuery 功能,可让您写入.css()
对象列表并处理它们。你需要类似的东西
ar = document.getElementsByTagName("code");
for (i = 0; i < ar.length; ++i)
ar[i].style.display = "none";
如果您需要切换code
可见性,请使用此代码
ar = document.getElementsByTagName("code");
for (i = 0; i < ar.length; ++i)
{
if(ar[i].style.display != "none") //the element is visible
{
ar[i].style.display = "none";
}
else
{
ar[i].style.display = "block"; //If you need to make it block explicitly, otherwise ""
}
}
请注意,该style.display
属性最初为空,默认为inline
forcode
标签,但可以显式设置为其他值。将其重置为会''
导致恢复状态。
如果需要在不修改显示模式的情况下来回更改可见性,则需要保存之前的模式(code
标签不仅可以在block
模式下显示)。可以这样做:
ar = document.getElementsByTagName("code");
for (i = 0; i < ar.length; ++i)
{
if(ar[i].style.display != "none") //the element is visible, "" or "blocK" or some other value
{
ar[i].saved_display = ar[i].style.display; //Save the display mode to a new property of the tag
ar[i].style.display = "none"; //And hide the element
}
else
{
if (typeof ar[i].saved_display === "undefined") //It's the first time we see the element. Display it in default mode
ar[i].style.display = "";
else
ar[i].style.display = ar[i].saved_display; //We know how the element was shown before we hid it, restoring
}
}