我正在尝试创建一个文本框,用户可以在其中键入其中一个颜色关键字,如蓝色,石灰或黑色,单击“提交”,页面背景颜色也会相应更改。
这就是我所拥有的:
<label for="color">Color: </label><input type="text" name="color" size="20" id="color" />
<button type="button" onClick="javascript:changeBGC(color)">Submit</button>
然后在我的脚本中
function changeBGC(color){
document.bgColor = color;
}
答案 0 :(得分:6)
试试这个:
document.body.style.backgroundColor = document.getElementById('color').value;
document.getElementById('color')
是输入元素,.value
获取它的值。
Here's some more documentation关于如何通过JavaScript设置CSS样式。
<强> Fiddle example 强>
答案 1 :(得分:0)
或者您可以将标记更改为以下内容:
<button type="button" onClick="javascript:changeBGC(color.value)">Submit</button>
^
答案 2 :(得分:0)
或者您可以使用更好的方法
<label for="color">Color:</label>
<input type="text" name="color" size="20" id="color" value=""/>
<button type="button">Submit</button>
var input = document.getElementById('color');
var button = document.querySelector('button');
button.addEventListener('click', function( event ) {
event.preventDefault();
var color = input.value;
document.body.style.background = color;
});