单击HTML时更改文本的颜色 [英] Changing color of text on click HTML

查看:163
本文介绍了单击HTML时更改文本的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习HTML。我必须做一个练习,文字必须从红色变为绿色。
我的代码在下面,但似乎不起作用。任何帮助将不胜感激。

  .red {color:#FF0000} 
.green {color:#00FF00; }
< script type ='text / javascript'>
function f(){
value = 1
if(value == 1){
document.getElementById(txt)。className =green;
value = 0
}
else if(value == 0){
document.getElementById(txt)。className =red
value = 1
}
}
< / script>
< p id ='i1'>这是< em>特殊< / em> < span id =txtclass ='red'> text< / span>。< / p>
< p id =点击onclick ='f();'>点击更改文字的颜色< / p>


解决方案

不要设置任何值。直接检查 txt class。

  function f(){
var txt = document.getElementById(txt);

if(txt.className =='green'){
txt.className =red;
}
else {
txt.className =green;
}
}

https://jsfiddle.net/fNPvf/33526/

I'm currently learning HTML. I have to do an exercice where a text must change back and forth from red to green. The code I have is below but doesn't seem to work. Any help would be appreciated.

.red { color : #FF0000 }
.green {color : #00FF00; }
<script type='text/javascript'>
function f(){
  value=1
  if (value == 1) {
    document.getElementById("txt").className = "green";
    value = 0 
  }
  else if (value == 0) {
    document.getElementById("txt").className="red"  
    value = 1
  }
}
</script>
<p id='i1'>This is <em> special </em> <span id="txt" class='red'>text</span>.</p>
<p id="click"  onclick='f();'>Click to change the colour of text</p>

解决方案

Don't set any value. Check directly txt class.

function f(){
  var txt = document.getElementById("txt");

  if (txt.className == 'green') {
   txt.className = "red";
  }
  else {
    txt.className = "green";
  }
}

https://jsfiddle.net/fNPvf/33526/

这篇关于单击HTML时更改文本的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆