【问题标题】:change color of a text in html using javascript使用javascript更改html中文本的颜色
【发布时间】:2017-07-21 12:36:12
【问题描述】:

我正在使用单独的.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)
    })
}

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    一些建议:

    1. 使用document.body 而不是getElementsByTagName('body')
    2. 在行尾使用分号(说明)
    3. addEventListener函数外创建state var
    4. 如果在 if() 条件下比较值,请使用 ===== 而不是 =

    var button = document.createElement('button');
    button.innerHTML = 'Red or green';
    
    document.body.appendChild(button);
    
    var state = 0;
    
    button.addEventListener('click', function (){
       var demo =  document.getElementById("demo");
    
       if (state === 1) {
         demo.style.color = 'red';
         state = 0;
         } else {
           demo.style.color = 'green';
           state = 1;
        }
    });
    <html>
    <body>
    <p id="demo">Click the button to change the text in this paragraph.</p>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多