Javascript 单击时更改文本颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2091326/
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-22 22:44:37  来源:igfitidea点击:

Changing text color onclick

javascript

提问by Patel

I'm new to JavaScript. I've developed a page using JavaScript in such a way that when I select a color it is applied to the whole page as a background.

我是 JavaScript 的新手。我使用 JavaScript 开发了一个页面,当我选择一种颜色时,它会作为背景应用于整个页面。

I want to develop a page where I can change only the text color. It should get changed (from red to green or something like that), but the page shouldn't get refreshed, and only the selected contents or text color should be changed.

我想开发一个只能更改文本颜色的页面。它应该被改变(从红色到绿色或类似的东西),但页面不应该被刷新,只应该改变选定的内容或文本颜色。

Can any one please help me in this. Any ideas of how to develop it? Thanks in advance.

任何人都可以帮助我。关于如何开发它的任何想法?提前致谢。

采纳答案by Erik

A rewrite of the answer by Sarfraz would be something like this, I think:

Sarfraz 对答案的重写将是这样的,我认为:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

您要么必须将此脚本放在页面底部,就在结束正文标记之前,要么将处理程序分配放在名为 onload 的函数中 - 或者如果您使用的是 jQuery,则非常优雅 $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc();the function would actually execute when the handler is being set.

请注意,当您以这种方式分配事件处理程序时,它会从您的 HTML 中删除功能。另请注意,您将其设置为等于函数名称 -- no ()。如果您这样做,onclick = myFunc();该函数将在设置处理程序时实际执行。

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

我很好奇 - 你知道足够的脚本改变背景颜色,但不是文本颜色?奇怪的:)

回答by Sarfraz

Do something like this:

做这样的事情:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

回答by Divya Pusuluru

   <p id="text" onclick="func()">
    Click on text to change
</p>
<script>
function func()
{
    document.getElementById("text").style.color="red";
    document.getElementById("text").style.font="calibri";
}
</script>