我不知道为什么底部的样式没有改变。 我试图保存该值并用它来改变底部的颜色但它没有改变。控制台中没有出现语法错误,所以我想我在这方面没问题。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<link rel="stylesheet" href="main.css">
<title>testing</title>
</head>
<body id="body">
<form>
<input type="bottom" class="btn" id="Cgreen" value="click here for green" onclick="changeColor()">
<input type="bottom" class="btn" id="Cblue" value="click here for blue" onclick="changeColor()">
</form>
<script>
var colorg = document.getElementById("Cgreen").value;
var colorb = document.getElementById("Cblue").value;
function changeColor() {
console.log (colorb + colorg);
if (colorb === "click here for blue") {
document.getElementById("Cblue").style = "blue";
} else if ( colorg === "click here for green") {
document.getElementById("Cgreen").style = "green";
}
}
</script>
</body>
</html>
最佳答案
这里有多个问题。
type="bottom"
无效。也许你的意思是键入type="button"
?
您不能直接将元素的
样式
设置为颜色。你必须更具体。你是说背景色吗?文字颜色?边框颜色?
如果你想改变背景的颜色,考虑这样的事情:
document.getElementById("Cblue").style.backgroundColor = "blue";
您的
if
逻辑没有意义。它说 “如果页面加载时蓝色按钮的值是“单击此处为蓝色”,则该函数应将其更改为蓝色。”这将始终 为真,因此无论您点击什么或做什么,这都是唯一会发生的事件。
与其使用条件逻辑,不如将您想要的颜色作为参数/参数传递到函数中。此外,如果您不想更改单击的元素,而是更改不同 元素,您也可以将其作为参数传递。
基本示例:
function changeColor(elem, color) {
elem.style.backgroundColor = color;
}
<input type="button" onclick="changeColor(this, 'blue');" value="Click for blue">
<input type="button" onclick="changeColor(this, 'green');" value="Click for green">
关于javascript - 如何用javascript改变底部的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211920/