如何使用JavaScript改变文本的字体颜色 |
您所在的位置:网站首页 › html改字体颜色大小代码怎么写 › 如何使用JavaScript改变文本的字体颜色 |
如何使用JavaScript改变文本的字体颜色
这个教程教我们如何使用JavaScript来改变文本的字体颜色。在使用JavaScript并开发应用程序的前端时,当事件发生时需要使用JavaScript来改变文本的字体颜色。 例如,我们有一个可以打开或关闭设备的应用程序。我们有一个按钮可以打开或关闭设备。当设备打开时,将按钮文本设置为绿色。否则,将按钮文本设置为红色。 所以,在这种情况下,程序员需要使用JavaScript来改变字体颜色。我们有一些不同的方法来解决这个问题,如下所示。 访问元素并改变样式在本节中,我们将使用JavaScript按id或类名访问元素。用户可以使用 .style 属性来改变元素的样式。此外,我们还可以改变特定的样式,如元素颜色、背景颜色、大小等。 在我们的例子中,我们将改变颜色属性值来改变字体颜色。用户可以按照以下语法使用JavaScript改变字体颜色。 语法 let element = document.getElementById(' element_id '); element.style.color = colorCode; 参数 colorName − 这是用户想要应用于文本的新颜色。它可以是颜色名称、颜色的十六进制代码或RGB值。 例子在下面的例子中,我们创建了一个按钮。当用户点击该按钮时,我们将调用一个名为 changeFontColor() 的函数。在函数内部,我们使用其id访问按钮元素,并使用其样式的颜色属性来更改颜色。 button { height: 30px; width: 100px; } Change the font color using JavaScript. Click the button to change the color of font inside the button. change color // function to change the font color of button function changeFontColor() { let button = document.getElementById("btn"); // access the button by id let color = button.style.color; if (color == "red") { // if button color is red change it green otherwise change it to red. button.style.color = 'green'; } else { button.style.color = 'red'; } }当用户点击“更改颜色”按钮时,按钮的颜色将在绿色和红色之间进行切换。 更改所有文本的颜色在这个部分,我们将学习如何更改所有正文文本的颜色。您可以考虑以下情况。当我们将深色或浅色主题应用到应用程序时,逐个更改每个元素的颜色并不是一个好的做法。相反,我们可以通过一次点击更改所有正文文本的颜色。 用户可以按照下面的语法来更改正文文本的字体颜色。 语法 document.body.style.color = color 示例在下面的示例中,我们将更改所有正文文字的颜色,而不是更改特定元素的文本。 button { height: 30px; width: 100px; } body { color: blue; } Change the font color using JavaScript. Click the button to change the color of font of the whole body change color // function to change the font color of button function changeFontColor() { // toggle the body text color on button click. let color = document.body.style.color; if (color == "blue") { document.body.style.color = 'pink'; } else { document.body.style.color = 'blue'; } }当用户点击按钮时,它会改变所有文字的颜色在粉红色和蓝色之间。 使用String的fontcolor()方法在这个部分,我们将学习关于 fontcolor() 方法。我们可以将 fontcolor() 方法应用在任何文本字符串上,并且它返回具有颜色属性的 HTML元素。 用户可以按照以下语法使用 fontcolor() 方法。 语法 let text = "some text"; text.fontcolor("color"); 参数 color −它是一个颜色代码或颜色名 返回值 fontcolor()方法返回HTML元素。 some text 示例在下面的例子中,我们将使用String的fontcolor()方法来改变特定字符串的颜色。 button { height: 30px; width: 100px; } Change the font color using JavaScript. Click the button to change the color of below text using fontcolor() method. hello world! change color // function to change the font color of button function changeFontColor() { let fontsDiv = document.getElementById("fonts"); let string = "hello world"; fontsDiv.innerHTML = string.fontcolor("green"); }在输出中,用户可以观察到当他们点击按钮时,“hello world”的字体变为绿色。 在本教程中,我们学习了如何通过一次点击来更改整个页面的文本。同时,我们还学习了如何使用元素的style属性来改变单个元素的文本颜色。在最后一部分中,我们学习了已弃用的fontcolor()方法,因此不建议使用该方法。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |