【问题标题】:How do I toggle the text colour of an html element when it is clicked?单击时如何切换html元素的文本颜色?
【发布时间】:2020-02-29 03:32:57
【问题描述】:

我想在单击 html 元素时更改它的颜色。我不希望文本本身改变,只是颜色。颜色应该随着随后的点击来回切换。感谢您的任何帮助。

【问题讨论】:

    标签: html text colors toggle


    【解决方案1】:

    这里有工作示例:

    let flag = true
    function toggleColor() {
      const exampleStyle = document.getElementById("example").style
      flag ? exampleStyle.color = "red" : exampleStyle.color = "blue"
      flag = !flag
    }
    <div id="example" onclick="toggleColor()">your text</div>

    【讨论】:

      【解决方案2】:

      如果要切换字体颜色,请使用:

      var h1=document.querySelector("h1");
      var iscolor=true;
      h1.addEventListener("click",function(){
      if (iscolor){
      h1.style.color="yellow";
      iscolor=false;}
      else{h1.style.color="black";
      iscolor=true;
      }
      
       });
      

      【讨论】:

      • 您好,感谢您的评论。你的代码和我的 html 标签有什么关系?
      • 这是 JavaScript。您可以在 中键入上述代码。然后它工作。更多,您将在第一行编写您的 html 标签/id/class 而不是 h1。比如,var element=document.queryselector("html tag/id/class");
      • 谢谢,我明白了。
      【解决方案3】:

      我认为在简单的场景中,您的解决方案应该与此类似

      var element = document.querySelector('your-element-selector');
      
      element.addEventListener('click', function(e) {
         element.style.backgroundColor = 'wanted color';
      });
      

      【讨论】:

      • 您好,感谢您的建议。这是html还是css?我无法让它在我的 html 文档中工作。
      • 这是javascript。您可以将其插入到您的 html 页面中,只需将代码包装到脚本标记中并放置在页面末尾 类似这样的内容:
      【解决方案4】:

      只需使用javascript:

      <span id="demo" onclick="clicked()">your text</span>
      <script type="text/javascript">
           function clicked() {
                document.getElementById("demo").style.color = "red";
           }
      </script>
      

      【讨论】:

      • 您好,感谢您的建议,效果很好,但如果再次单击,我需要将文本切换回原始颜色 - 抱歉,我应该说清楚。
      • 所以你想创建切换系统?
      • 嗨,是的,没错。上述 cccn 的解决方案有效,但我也对任何其他解决方案感兴趣。谢谢:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2016-01-14
      • 2020-02-08
      相关资源
      最近更新 更多