我想使用红色和蓝色按钮将我的时钟颜色更改为红色和蓝色,但由于某种原因无法正常工作。如果有人可以看一下我的代码并帮助我,那就太好了。我已经在 youtube 和谷歌上查找了 awnser,但无济于事。
HTML:
<html>
<head>
<title> Clock II & III </title>
<link rel="stylesheet" type="text/css" href="clock.css">
<script type = "text/javascript">
var x = 0;
function renderTime() {
var currentTime = new Date();
var diem = "AM"
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockdisplay')
myClock.innerHTML = h + ":" + m + ":" + s + " " + diem;
}
window.onload = function() {
renderTime();
setInterval(renderTime, 1000);
};
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;
}
}
function reveal() {
document.getElementById('clockdisplay').className = 'bluetext';
}
function hide() {
document.getElementById('clockdisplay').className = 'redtext';
}
</script>
</head>
<body>
<div id = "clockdisplay" class = "clockStyle">
22:23PM
</div>
<button class = "Btnred" onclick = "reveal()"> Red </button>
<button class = "Btnblue" onclick = "hide()"> Blue </button>
<body>
</html>
CSS:
#clockdisplay {
background-color:#000;
border:#999 2px inset;
padding:6px;
color:#0FF;
font-family:"Ariel Black", Gadget, sans-serif;
font-size:16px;
font-weight:bold;
letter-spacing:2px;
display:inline;
}
.bluetext {
color:blue;
}
.redtext {
color:red;
}
最佳答案
问题是为 #clockdisplay
定义的样式比为 .bluetext
和 .redtext
类设置的样式具有更高的优先级。所以颜色 color: #0FF;
总是被应用,即使你添加类也是如此。
你可以这样修复它:
#clockdisplay.bluetext {
color: blue;
}
#clockdisplay.redtext {
color: red;
}
演示:http://jsfiddle.net/j2r8ksa2/
关于javascript - 使用按钮javascript更改某些东西的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27273142/