如何使用一个按钮将CSS样式应用于具有相同ID的所有元素? [英] How to apply CSS style to all elements with same ID using one button?

查看:168
本文介绍了如何使用一个按钮将CSS样式应用于具有相同ID的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的想法是创建一个按钮来隐藏/显示所有隐藏的文本(通过以黑色突出显示文本来隐藏,通过使文本的背景颜色透明来进行显示).但是,如下所示,这些代码仅适用于具有给定ID("p2")的第一个元素.

My idea was to create a button to hide/show all hidden text (Hide by highlighting the text in black, show by making the background color of the text transparent). But the codes, as shown below, only works for the 1st element with the given ID ("p2").

Javascript:

Javascript:

function change()
{
    var test = document.getElementById("button1");
    if (test.value=="Hide Spoiler") 
    {  
        test.value = "Open Spoiler"; 
        document.getElementById("p2").style.backgroundColor="black";  
    }
    else  
    {  
        test.value = "Hide Spoiler"; 
        document.getElementById("p2").style.color="black";
        document.getElementById("p2").style.backgroundColor="transparent";  
    }
}

HTML:

<input onclick="change()" type="button" value="Open Curtain" id="button1"></input>
<br>
<span id="p2">Hidden text</span> Test for more <span id="p2">Hidden text</span> test again. <span id="p2">Hidden text</span>

如何仅用1个按钮使所有具有相似ID的元素更改其CSS样式?谢谢.

How would I make all the elements with similar ID to change its CSS style using only 1 button? Thanks.

推荐答案

您的代码只会更新一个元素,因为getElementById只会返回一个元素(因为正如我们所说,id应该是唯一的).如果需要将多个元素标记为相关元素,请使用class. 这是一个使用class ,JavaScript的有效示例:

Your code is only every going to update one element, because getElementById will only ever return one element (because, as we've said, id is supposed to be unique). If you need to mark multiple elements as related use a class instead. Here is a working example using class, JavaScript:

function change() {
    var test = document.getElementById("button1");
    var els = document.getElementsByClassName("p2");
    if (test.value == "Hide Spoiler") {
        test.value = "Open Spoiler";
        for (var i=0; i<els.length; i++) {
            els[i].style.backgroundColor = "black";
        }
    } else {
        test.value = "Hide Spoiler";
        for (var i=0; i<els.length; i++) {
            els[i].style.color = "black";
            els[i].style.backgroundColor = "transparent";
        }
    }
}

HTML:

<input onclick="change()" type="button" value="Hide Spoiler" id="button1"></input>
<br>
<span class="p2">Hidden text</span> Test for more <span class="p2">Hidden text</span> test again. <span class="p2">Hidden text</span>

如果您需要它在对getElementsByClassName而言过旧的浏览器中运行,请尝试使用 jQuery .它使这种事情变得更容易

If you need it to work in browsers too old for getElementsByClassName, try using jQuery. It makes this sort of thing lots easier

这篇关于如何使用一个按钮将CSS样式应用于具有相同ID的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆