2013-01-07 2 views
2

ID가 foo 인 HTML 요소의 배경색을 변경하고 싶습니다. 나는 현재이 코드를 가지고 :JavaScript로 CSS 값을 설정하는 방법은 무엇입니까?

var hexcode = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'); 

// this chooses a random value from the array hexcode 
var ranval = function() { 
    return hexcode[Math.floor(Math.random()*hexcode.length)]; 
} 

// six ranval() are put together to get color 
var colorname = "#" + ranval() + ranval() + ranval() + ranval() + ranval() + ranval(); 

// trying to put the value on the background of element with "foo" ID. 
document.getElementById("foo").style.color = colorname; 

이 코드는이 오류를 던지고있다 : 나는 ID foo의 존재를 확신

Uncaught TypeError: Cannot read property 'style' of null 

.

+1

당신은 긍정적인가? '

4

DOM 준비가되기 전에 요소에 액세스하려고하기 때문에 오류가 발생합니다. 윈도우를 액세스하기 전에로드 될 때까지 기다립니다 :

// Credit: http://paulirish.com/2009/random-hex-color-code-snippets/ 

function random_color() { 
    return '#' + ('00000' + (Math.random() * 16777216 << 0).toString(16)).substr(-6); 
} 

window.onload = function() { 
    document.getElementById("foo").style.backgroundColor = random_color(); 
}; 

데모 : 코드를 해결하기 위해 http://jsfiddle.net/Blender/xQure/1/

+0

오류는 발생하지 않지만 색상은 변경되지 않습니다 ../ –

+0

6 자 이하의 숫자를 얻으면 색상이 변경되지 않거나 잘못 변경되므로 스크립트에 @Blender 오류가 발생합니다. –

+0

@GabrielGartz : 고마워, 잘 됐어. – Blender

관련 문제