如何通过单击按钮更改文本颜色?
问题描述:
我有如下文字:
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>
我想在单击按钮时更改文本颜色.
I want to change the text color when I click the button.
答
使用 addEventListener('click')
将 click
事件附加到按钮,然后更改您的按钮的颜色使用 .style.color = 'color'
的文本,请查看下面的示例.
Attach click
event to the button using addEventListener('click')
then change the color of your text using .style.color = 'color'
, check example below.
注意:如果你给你的元素一个标识符会更好.
NOTE : It will be better if you give your elements an identifier.
希望这会有所帮助.
document.querySelector('button').addEventListener('click', function(){
document.querySelector('p').style.color='green';
})
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER</button>