Как сделать, чтобы при нажатии на кнопку менялся фон?

Рейтинг: 0Ответов: 3Опубликовано: 26.05.2011

Хочу создать кнопку, чтоб при нажатии на нее менялся фон страницы?

Ответы

▲ 5

Если нужно рамдомизировать выбор цвета, то можно сделать так.

<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function() {
    var button = document.getElementById('input_button_bg_change');
    var body = document.getElementsByTagName('body')[0];
    var colors = ['blue', 'grey', 'black', 'white', 'red', 'green', '#aaa', '#FFAACC', 'rgb(122,111,110)'];
    button.onclick = function() {
        body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    };
};
</script>
</head>
<body>
    <input type="button" id="input_button_bg_change" value="Change background color"/>
</body>
</html>
▲ 2
<input type="button" />

Добавлено.

И через функцию:

onclick='switchBg();'

var bgar = ['#f00', '#0f0', '#00f'], curBg = 0;
function switchBg(){ 
    document.body.style.background = bgar[++curBg % bgar.length];
}
▲ 2

Код не проверял на работоспособность

<script>
var colorArray = [ "#000", "#fff", "#eee" ]; // массив с цветами
var i = 0; // итератор

function changeColor(){
    document.body.style.background = colorArray[i]; 
    i++;
    if( i > colorArray.length - 1){
        i = 0;
    }
}

</script>
<input type="button"/>