javascript - 使用javascript更改html中文本的颜色

标签 javascript jquery html

我正在使用单独的 .js 文件更改某些文本的颜色。我是 HTML 和 JavaScript 的新手,请详细说明。谢谢。

这是我到目前为止得到的:

htmlfile.html

<html>
<body>
    <p id="demo"> Click the button to change the text in this paragraph. </p>
</body>
</html>

jsfile.js

    var button = document.createElement("button")
    button.innerHTML = "Red or green"
    // Sets or returns the content of an element

    // 2. Append somewhere
    var body = document.getElementsByTagName("body")[0]
    body.appendChild(button)
    // Adds a new child node, to an element, as the last child node

    // 3. Add event handler
    button.addEventListener("click", function () {
        state = !state
        // Attaches an event handler to the specified element

        //var led = document.createElement('LED')
        if (state = 1) {
            document.getElementById("demo").style.color = "red"
        } else {
            document.getElementById("demo").style.color = "green"
        }
        //body.appendChild(led)
    })
}

最佳答案

status = 1;
function switchStyle() {
x = document.getElementById("text");
if(status==1) {
    x.style.color = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.color = 'red';
    status = 1;
}
}
<p id="text">This text color will change.</p><br>
<button type="button" onclick="javascript:switchStyle();">Switch Style</button>

关于javascript - 使用javascript更改html中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42544346/

相关文章:

javascript - 在表单提交之前获取单选按钮的值

javascript - Accordion 显示全部内容

Microsoft Dynamics CRM 2013 的 Javascript 兼容性错误

javascript - storage.removeItem - 我如何使用它从值而不是键中删除多个项目

html - 浏览器的 1px 计算问题(亚像素问题)

javascript - 如何知道何时应用了 font-face

jquery - 避免 html 表格在鼠标悬停时闪烁

javascript - setTimeout 变量中的函数被覆盖

javascript - 从下拉菜单中删除下拉(选择)按钮?

html - 在样式属性中使用导入