我一直在尝试通过输入和抛入函数的文本颜色来更改文本颜色,但我不知道哪里出错了。我已经使用了参考代码并改变了一两个值,所以我假设我弄乱了一些东西。这是我遇到问题的代码:
<form>
<input id="newColor" type="text"> <button value="Text" onclick="changeText(tColor)">Text</button>
</form>
<br>
<div id="divTag">
THIS TEXT HERE
</div>
<script>
function changeText(tColor)
{
document.getElementById("newColor").value = tColor.value;
document.getElementById("divTag").style.backgroundColor = tColor;
}
</script>
这真让我烦恼。我还需要更改页面背景颜色,但由于它的方式相同,我可以根据此代码进行学习。有人可以帮帮我吗?
答案 0 :(得分:1)
尝试将函数置于函数调用之上,并在tColor
周围包装单引号试试这个
<head>
<script type="application/javascript">
function changeColor(x,y){
var z = document.getElementById(y);
z.style.color = x;
}
</script>
</head>
<body>
<button id="button_1" onclick="changeColor('red','h1')">ChangeColor</button>
<span id="h1" style="color:blue;">Hello</span>
</body>
答案 1 :(得分:0)
我不知道tColor。但是作为一个例子,如果你想将文本颜色改为红色,那么你应该做的如下。
<script>
function changeText(tColor)
{
document.getElementById("newColor").style.color = tColor;
document.getElementById("divTag").style.backgroundColor = tColor;
}
</script>
<form onsubmit="return false;">
<input id="newColor" type="text"> <button value="Text" onclick="changeText('red')">Text</button>
</form>
<br>
<div id="divTag">
THIS TEXT HERE
</div>
JsFiddle 如果你想从'newColor'文本框中获取颜色,代码应该改变如下。
<script>
function changeText()
{
var sColor = document.getElementById('newColor').value;
document.getElementById("newColor").style.color = sColor;
document.getElementById("divTag").style.backgroundColor = sColor;
}
</script>
希望你能得到答案..
答案 2 :(得分:0)
这会解决你的问题:
<?php
if(isset($_POST['color'])){
if($_POST['color'] != ""){
$color = $_POST['color']; // be sure and sanitize this
echo $color;
exit();
} else {
echo "error";
exit();
}
}
?>
<html>
<head>
<script type="application/javascript">
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
<script type="application/javascript">
function _(x) {
return document.getElementById(x);
}
</script>
<script type="application/javascript">
function changeColor() {
var color = _("newColor").value;
if (color == ""){
} else {
var ajax = ajaxObj("POST", "<?php echo $_SERVER['PHP_SELF'] ?>");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "error") {
} else {
var newColor = ajax.responseText;
var ele = _("divTag");
ele.style.color = newColor;
}
}
}
ajax.send("color="+color);
}
}
</script>
</head>
<body>
<form onsubmit="return false;">
<input id="newColor" type="text">
<button value="Text" onclick="changeColor()">Change Color</button>
</form>
<br>
<div id="divTag">THIS TEXT HERE</div>
</body>
</html>