2013-02-16 85 views
0

我的功能用于工作,但现在不行。我试图添加一个if语句,当输入空白时,它会返回到默认的背景色。基于JavaScript输入的背景更改?

var path = /^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/g; 

function col(obj) { 
    var val = obj.value; 
    if (path.test(val)) { 
     document.body.style.backgroundColor = '#' + val; 
    } 
} 

window.onload = function() { 
    document.getElementById('bgcol').onkeyup = function() { 
     col(this); 
    } 
    if (getElementById('bgcol'.value = null || ""){ 
    document.body.style.backgroundColor = '#000000'; 
} 
} 

//结束的javascript,开始下面

<input id="bgcol" placeholder="enter hexadecimal color"></input> 

回答

0

Working Fiddle

if (getElementById('bgcol').value == "") { 

document.getElementById('bgcol').onkeyup = function() { 
    if (this.value == ""){ 
     document.body.style.backgroundColor = '#000000'; 
    } 
    else { 
     col(this); 
    } 
} 

012的html
<input id="bgcol" placeholder="enter hexadecimal color" /> 
+1

难道没有人打扰,甚至在他们的头脑测试代码? – 2013-02-16 17:25:06

+0

@Kolink是的,我明白了,我的错误是,'OR'门没有被使用,因为它应该是。 – 2013-02-16 17:26:31

+0

@Kolink现在怎么样? – 2013-02-16 17:32:26

-1

试试你的代码的这种简化版本:

window.onload = function() { 
    document.getElementById('bgcol').onkeyup = function() { 
     var col = this.value; 
     if(!col.match(/^#?(?:[0-9a-f]{3}){1,2}$/i)) col = "#000000"; 
     if(col.charAt(0) != "#") col = "#"+col; 
     document.body.style.backgroundColor = col; 
    }; 
}; 

它使用一个简单的正则表达式,也允许#被接受和可选。

0

你需要document.getElementById和清理你的语法:

if (document.getElementById('bgcol').value == null || document.getElementById('bgcol').value == "")