在 javascript onClick 中设置字体颜色的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8057895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:33:47  来源:igfitidea点击:

Easy way to set font color in javascript onClick?

javascripthtmlweb

提问by facebook-1389780026

Question: So let's say I have some basic code

问题:假设我有一些基本代码

    <a name = "sec">this is a test</a>

I want a javascript function to on click of a link to change that to

我想要一个 javascript 函数点击一个链接将其更改为

So user clicks: link!

所以用户点击:链接!

And the JS kicks in to change the 1st html to:

并且 JS 开始将第一个 html 更改为:

    <font color = "green"><a name = "sec">this is a test</a></font>

Is it possible to do this in JS?

可以在 JS 中做到这一点吗?

回答by joshuahedlund

You can set the element's color with JS as a simple solution. You should also give the element a valid href attribute that nullifies the default click behavior.

您可以使用 JS 设置元素的颜色作为一个简单的解决方案。您还应该为元素提供一个有效的 href 属性,以取消默认的点击行为。

<a name="sec" href="javascript:void(0);" onclick="this.style.color='green';">
  this is a test
</a>

回答by ayanami

Try something along the lines of

尝试一些类似的东西

<a href="#" onclick="this.style.color='green'; return false;">link</a>

And you should not use <font>tag for setting text attributes, this is considered bad practice in today's HTML (be it XHTML or HTML5).

并且您不应该使用<font>标签来设置文本属性,这在当今的 HTML(无论是 XHTML 还是 HTML5)中被认为是不好的做法。

回答by downed

Something like this should work: (Psudeo Code)

这样的事情应该可以工作:(伪代码)

<a id="sec" onClick="makeGreen()">this is a test</a>

<script type="text/javascript" charset="utf-8">

function makeGreen() {
     document.getElementById('sec').style.color('green');
};

</script>

回答by scurker

Realistically, you should keep your semantics and your style separate. As other users have suggested, use a css class instead of modifying styles directly. This is fairly easy to do, as shown by this jsFiddle

实际上,您应该将语义和风格分开。正如其他用户所建议的,使用 css 类而不是直接修改样式。这很容易做到,如this jsFiddle所示

<a href="#" id="my-link">This is a test</a>

<script type="text/javascript">
  var el = document.getElementById('my-link');
  el.addEventListener('click', function() {
    this.className = 'clicked-class';
  });
</script>

And of course in your CSS you would define some sort of rule:

当然,在你的 CSS 中你会定义某种规则:

.clicked-class {
  color: green;
}

This could be made even simpler with a javascript library of your choice, but hopefully should be enough to get you started.

使用您选择的 javascript 库可以使这更简单,但希望应该足以让您入门。

回答by Yogev Izhak

the easy/fast way is

简单/快速的方法是

$(click_element).on('click',function() {
$(target_element).css('color', 'blue')});