javascript - 如何用javascript改变底部的样式?

标签 javascript html css

我不知道为什么底部的样式没有改变。 我试图保存该值并用它来改变底部的颜色但它没有改变。控制台中没有出现语法错误,所以我想我在这方面没问题。

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
        <meta charset="utf-8">
        <link rel="stylesheet"  href="main.css">
        <title>testing</title>
    </head>
    <body id="body">
        <form>
            <input type="bottom"  class="btn" id="Cgreen" value="click here for green" onclick="changeColor()">
            <input type="bottom"  class="btn" id="Cblue" value="click here for blue"  onclick="changeColor()">
        </form>

        <script>
            var colorg = document.getElementById("Cgreen").value;
            var colorb = document.getElementById("Cblue").value;

            function changeColor() {
                console.log (colorb + colorg);
                if (colorb === "click here for blue") {
                    document.getElementById("Cblue").style = "blue";
                } else if ( colorg === "click here for green") {
                    document.getElementById("Cgreen").style = "green";
                }
            }
        </script>
    </body>
</html>

最佳答案

这里有多个问题。

  1. type="bottom" 无效。也许你的意思是键入 type="button"

  1. 您不能直接将元素的样式设置为颜色。

    你必须更具体。你是说背景色吗?文字颜色?边框颜色?

    如果你想改变背景的颜色,考虑这样的事情:

    document.getElementById("Cblue").style.backgroundColor = "blue";
    

  1. 您的 if 逻辑没有意义。

    它说 “如果页面加载时蓝色按钮的值是“单击此处为蓝色”,则该函数应将其更改为蓝色。”这将始终 为真,因此无论您点击什么或做什么,这都是唯一会发生的事件。

    与其使用条件逻辑,不如将您想要的颜色作为参数/参数传递到函数中。此外,如果您不想更改单击的元素,而是更改不同 元素,您也可以将其作为参数传递。

    基本示例:

function changeColor(elem, color) {
    elem.style.backgroundColor = color;
}
<input type="button" onclick="changeColor(this, 'blue');" value="Click for blue">
<input type="button" onclick="changeColor(this, 'green');" value="Click for green">

关于javascript - 如何用javascript改变底部的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211920/

相关文章:

javascript - focusout 时显示警报,仅一次

javascript - 如果您只是在页面上定义一个新标签会怎样? (没有网络组件)

html - 网页设计在桌面 PC 显示器中失真

css - 使用 Express 应用程序,如何在 css/stylus 中使用我的模式数据?

javascript - 在 Coldfusion 或 JavaScript 中创建标签云

javascript - 通过交互更新凹坑多系列图表中的系列顺序

html - html 时事通讯中的 google webfonts

javascript - 如何删除 "printing"html 的 href 到 PDF?

javascript - AngularJS : Understanding service when using $http. 帖子

javascript - 使用WebClient类返回图像数据并在标签中渲染图像