我有一个文本类似以下内容:如何用按钮点击改变文字颜色?
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>
我想改变文字颜色,当我按一下按钮。
我有一个文本类似以下内容:如何用按钮点击改变文字颜色?
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>
我想改变文字颜色,当我按一下按钮。
连接click
事件使用addEventListener('click')
然后更改使用.style.color = 'color'
文字的颜色,检查下面的示例中的按钮。
注意:如果你给你的元素一个标识符会更好。
希望这会有所帮助。
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>
请注意OP中没有jQuery标记。 –
而你在哪里看到我的答案jQuery? –
我可以知道哪些语言代码监听事件吗? –
首先,您需要使用document.getElementsByTagName("button")[0];
找到要更改颜色的元素,并将其存储在变量中。
接下来,使用button元素上的事件侦听器来侦听点击。
单击执行时,p
元素将其颜色更改为蓝色。
var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
document.querySelector('p').style.color = "blue";
});
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>
document.getElementsByTagName("button")[0].addEventListener("click",function() {
document.querySelector('p').style.color = "red";
});
<p id = 'textToChange'><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>
jQuery没有被指定为正在使用的框架 - 虽然没有人说... –
我同意,编辑:) –
@DanielShillcock检查修订版... –
指定ID /类元素,效果更佳。
$("input[type=button]").click(function() {
$("p").css("color", "red");
});
要小心在OP没有jQuery标签... –
function changeColor(){
var element = document.getElementById("questionContainer");
element.className = "myClass";
}
.myClass{
color:red;
}
<div id="questionContainer">
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
</div>
<button onclick="changeColor()">COLORCHANGER<button>
你有什么努力实现颜色的变化?显示一些你为此写的代码。 –
可能的重复[http://stackoverflow.com/questions/17925577/change-text-color-with-javascript](http://stackoverflow.com/questions/17925577/change-text-color-with-javascript) 。 –