【问题标题】:How to change the text color with button click?如何通过单击按钮更改文本颜色?
【发布时间】:2016-12-11 18:21:14
【问题描述】:

我有如下文字:

<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>

我想在单击按钮时更改文本颜色。

【问题讨论】:

标签: javascript html


【解决方案1】:

首先,您需要使用document.getElementsByTagName("button")[0]; 找到要更改颜色的元素并将其存储在变量中。

接下来,在按钮元素上使用事件监听器来监听点击。

当点击执行时,p 元素将其颜色变为蓝色。

var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
  document.querySelector('p').style.color = "blue";  
});
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
 <button>COLORCHANGER<button>

【讨论】:

    【解决方案2】:

    document.getElementsByTagName("button")[0].addEventListener("click",function() {
      document.querySelector('p').style.color = "red";  
    });
     <p id = 'textToChange'><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
     <button>COLORCHANGER<button>

    【讨论】:

    • jQuery 没有被指定为正在使用的框架——尽管没有人这么说...
    【解决方案3】:

    使用addEventListener('click')click 事件附加到按钮,然后使用.style.color = 'color' 更改文本颜色,请查看下面的示例。

    注意:最好给元素一个标识符。

    希望这会有所帮助。

    document.querySelector('button').addEventListener('click', function(){
        document.querySelector('p').style.color='green';
    })
    <p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
    <button>COLORCHANGER</button>

    【讨论】:

    • 注意 OP 中没有 jquery 标签。
    • 亲爱的它也是一种 JS,建立在 javascript 之上
    【解决方案4】:

    为元素指定 id/class 以获得更好的结果。

           $("input[type=button]").click(function () {
                $("p").css("color", "red");
            });
    

    【讨论】:

      【解决方案5】:

      function changeColor(){
      var element = document.getElementById("questionContainer");
      element.className = "myClass";
      }
      .myClass{
       color:red; 
       }
      <div id="questionContainer"> 
      <p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
        </div>
       <button onclick="changeColor()">COLORCHANGER<button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        • 2013-01-28
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        相关资源
        最近更新 更多