javascript - 如何通过单击 javascript 中的按钮来更改背景颜色和文本颜色?

标签 javascript html css

我正在尝试将三个不同的段落更改为遵循相同主题但不同的颜色(在示例中不明显,只是一个测试)。但是我不能让他们改变。 :( 我也愿意使用 JQuery 的方式来做到这一点。

HTML

<button onclick="white()">
        <p>White</p>
    </button>

    <button onclick="red()">
        <p>Red</p>
    </button>

    <button onclick="yellow()">
        <p>Yellow</p>
    </button>

    <button onclick="blue()">
        <p>Blue</p>
    </button>

    <h1>Hey There</h1>
    <ul class="list-unstyled">
        <li>Colors are cool</li>
        <li>Join the Rebellion!!!</li>
    </ul>


    <div class="colorbox" id="colorbox1">
        <h1>Div one</h1>
        <p>I'm 1</p>
    </div>

    <div class="colorbox" id="colorbox2">
        <h1>Div two</h1>
        <p>I'm 2</p>
    </div>

    <div class="colorbox" id="colorbox3">
        <h1>Div three</h1>
        <p>I'm 3</p>
    </div>

JavaScript

var colorbox1 = document.getElementsById('colorbox1');
var colorbox2 = document.getElementsById('colorbox2');
var colorbox3 = document.getElementsById('colorbox3');

function white() {
    colorbox1.style.backgroundColor = "white";
    colorbox1.style.color = "black";

    colorbox2.style.backgroundColor = "white";
    colorbox2.style.color = "black";

    colorbox3.style.backgroundColor = "white";
    colorbox3.style.color = "black";
}

function red() {
    colorbox1.style.backgroundColor = "red";
    colorbox1.style.color = "black";

    colorbox2.style.backgroundColor = "red";
    colorbox2.style.color = "black";

    colorbox3.style.backgroundColor = "red";
    colorbox3.style.color = "black";
}

function yellow() {
    colorbox1.style.backgroundColor = "yellow";
    colorbox1.style.color = "black";

    colorbox2.style.backgroundColor = "yellow";
    colorbox2.style.color = "black";

    colorbox3.style.backgroundColor = "yellow";
    colorbox3.style.color = "black";
}

function blue() {
    colorbox1.style.backgroundColor = "white";
    colorbox1.style.color = "black";

    colorbox2.style.backgroundColor = "white";
    colorbox2.style.color = "black";

    colorbox3.style.backgroundColor = "white";
    colorbox3.style.color = "black";
}

最佳答案

没有getElementsById()方法,只有getElementById()没有s

var colorbox1 = document.getElementById('colorbox1');
var colorbox2 = document.getElementById('colorbox2');
var colorbox3 = document.getElementById('colorbox3');

关于javascript - 如何通过单击 javascript 中的按钮来更改背景颜色和文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588406/

相关文章:

javascript - JSON.stringify(arguments) 是怎么回事?

html - 创建带箭头的背景 div

HTML 文本对齐 : center; doesn't work

html - Box-shadow 在 Chrome 中是黑色的,但在 Firefox 中是白色的?

javascript - div动画不重复点击jquery

jQuery 鼠标悬停在 IE、Opera、Chrome 中的奇怪行为

javascript - AngularJS - ng-options 完成填充选择后的 jquery 插件 SelectBoxIt

javascript - *整个*文档中某个元素之后的下一个元素

javascript - 从二进制字符串在 HTML 5 Canvas 上添加绘图图像时质量下降

javascript - 有条件地订阅/取消订阅多条消息