I am trying to change the color of my name, by clicking on a button. Here is what I've done till now,
<html>
<head><title></title></head>
<body>
<p id="demo">Sandeep Roy</p>
<button type="button" onclick="change()">Click</button>
<script>
function change() {
var x=document.getElementById("demo");
x.style.color=red;
}
</script>
</body>
</html>
The expected output is a red font, when 'click' button is clicked.
Unfortunately nothing happens when I do that, ie same black color font. Please help me educating in this matter.
In the below, you're missing quotas
var x=document.getElementById("demo");
x.style.color=red;
should be
var x=document.getElementById("demo");
x.style.color='red';
besides that - this approach is awful. Toggling classes is more preffered.
In this case red
is variable. You should use string instead. Use
x.style.color='red';
语法错误
x.style.color='red';
Correct - red color assign as a string name or value(hex color code like '#ff0000') of the color.
Syntax- object.style.color="color|initial|inherit"
x.style.color='red';
x.style.color='#ff0000';
You can see the live demo on Fiddler
<html> <head><title></title></head> <body> <p id="demo">Sandeep Roy</p> <button type="button" onclick="change()">Click</button> <script> function change() { var x=document.getElementById("demo"); x.style.color='red'; } </script> </body> </html>
在下面的行中缺少报价。
x.style.color='red';
Try this it works,
<html> <head><title></title></head> <body> <p id="demo">Sandeep Roy</p> <button type="button" onclick="change()">Click</button> <script> function change() { document.getElementById("demo").style.color = "red"; } </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.