Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   смена фона при клике (https://javascript.ru/forum/misc/62359-smena-fona-pri-klike.html)

vd1216 06.04.2016 19:36

смена фона при клике
 
Всем привет!
помогите, пожалуйста, разобраться что я делаю не так(
я только начала изучать JS и не могу понять как сделать чтобы при клике менялся фон с одного цвета на другой бесконечно и без перезагрузки. у меня почему то меняется только на оранжевый и все, и нужно перезагружать страницу
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	.sor{
		margin:50px auto;
		border:1px solid #000;
		padding:5px;
		border-radius:50%;
		background:red;
		width:20px;
		text-align:center;
	}
	</style>
	<script>
		window.onclick=function(){
			for(var i=1; i<5;i++){
			document.getElementById('sor').style.background = 'green';
			document.getElementById('sor').style.background = 'yellow';
			document.getElementById('sor').style.background = 'pink';
			document.getElementById('sor').style.background = 'orange';
		}
		}	
	
	</script>
</head>
<body>
	<div class="sor" id="sor" onclick="" type="button">
		7
	</div>
</body>
</html>

рони 06.04.2016 19:45

vd1216,
для начала Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[js]
... ваш код...
[/js]


О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

и уберите цикл, напишите массив со цветами и сделайте переменную для индекса, по клику увеличивайте индекс и берите цвет из массива по этому индексу.

Николай_777 14.05.2016 09:49

добрый день помогите пожалуйста с кодом код служит для смены фона при обновление страницы
<script>
$(document).ready(function () {
if (typeof (not_blocked) == 'undefined' || !not_blocked) {
var content_w = 1000;
var side_width = (window.innerWidth - content_w) / 2;
width = width > 0 ? width : 0;
jQuery('body').css({

'background': "url(http://www.ru/img/1.png) no-repeat scroll center top #000",
'padding-top': "150px"
});

$('body').prepend(
'<a id="ar_t12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: 100%; height: 150px;" href="http://" target="_blank"><img src="http://" width="1" height="1" /></a>'
);
$('body').prepend(
'<a id="ar_r12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; right: 0px; left: auto; width: ' + side_width + 'px; height: 850px;" href="http://" target="_blank"></a>'
);
$('body').prepend(
'<a id="ar_l12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: ' + side_width + 'px; height: 850px;" href="http://" target="_blank"></a>'
);

jQuery(window).resize(function () {
var side_width = (window.innerWidth - content_w) / 2;
side_width = side_width > 0 ? side_width : 0;
jQuery('#ar_r12, #ar_l12').css('width', side_width);
});
}
});
</script>

вопрос в том что надо добавить в <body> чтобы скрипт работал а именно менялся фон

рони 14.05.2016 10:38

Николай_777,
Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[js]
... ваш код...
[/js]


О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

Николай_777 14.05.2016 10:43

<script type="text/javascript">
		jQuery(document).ready(function () {
			
			if (typeof (not_blocked) == 'undefined' || !not_blocked) {
				var content_w = 1000;
				var side_width = (window.innerWidth - content_w) / 2;
				width = width > 0 ? width : 0;
				/* Брендирование */
				jQuery('body').css({
					'background': "url('http:// Фон сайта') no-repeat scroll center top #000",
					'padding-top': "150px"
				});
				// добавим ссылки
				jQuery('body').prepend(
					'<a id="ar_t12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: 100%; height: 150px;" href="http://ссылки кудато" target="_blank"><img src="http://ссылки кудато" width="1" height="1" /></a>'
				);
				jQuery('body').prepend(
					'<a id="ar_r12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; right: 0px; left: auto; width: ' + side_width + 'px; height: 850px;" href="http://ссылки кудато" target="_blank"></a>'
				);
				jQuery('body').prepend(
					'<a id="ar_l12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: ' + side_width + 'px; height: 850px;" href="http://ссылки кудато" target="_blank"></a>'
				);

	
				jQuery(window).resize(function () {
					var side_width = (window.innerWidth - content_w) / 2;
					side_width = side_width > 0 ? side_width : 0;
					jQuery('#ar_r12, #ar_l12').css('width', side_width);
				});
			}
		});
	</script>

рони 14.05.2016 10:52

Николай_777,
убрать строку 7 или переписать правильно, и добавить ссылку на фон в строке 10.

Николай_777 14.05.2016 11:11

<script>
		jQuery(document).ready(function () {
			// фигарим сюда брендирование напрямую!
			if (typeof (not_blocked) == 'undefined' || !not_blocked) {
				var content_w = 1000;
				var side_width = (window.innerWidth - content_w) / 2;
								/* Брендирование */
				jQuery('body').css({
					'background': "url('http://www.top-4f.ru/img/8975.jpg') no-repeat scroll center top #000",
					'padding-top': "150px"
				});
			    
				// добавим ссылки
				jQuery('body').prepend(
					'<a id="ar_t12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: 100%; height: 150px;" href="http://www.top-4f.ru/stuff/" target="_blank"><img src="http://www.top-4f.ru/stuff/" width="1" height="1" /></a>'
				);
				jQuery('body').prepend(
					'<a id="ar_r12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; right: 0px; left: auto; width: ' + side_width + 'px; height: 850px;" href="http://www.top-4f.ru/stuff/" target="_blank"></a>'
				);
				jQuery('body').prepend(
					'<a id="ar_l12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: ' + side_width + 'px; height: 850px;" href="http://www.top-4f.ru/stuff/" target="_blank"></a>'
				);

				// вешаем бинд на изменение размеров окна
				jQuery(window).resize(function () {
					var side_width = (window.innerWidth - content_w) / 2;
					side_width = side_width > 0 ? side_width : 0;
					jQuery('#ar_r12, #ar_l12').css('width', side_width);
				});
			}
		});
	</script>

фон появился спасибо но как реализовать смену фона при обновление страницы
если надо вот ссылка на сайт http://www.top-4f.ru/

рони 14.05.2016 11:30

Цитата:

Сообщение от Николай_777
как реализовать смену фона при обновление страницы

обьясните, про что вы?

Николай_777 14.05.2016 11:38

можно как нибудь сделать чтобы фон менялся при обновление страницы сайта
jQuery('body').css({
  'background': "url('http://www.top-4f.ru/img/8975.jpg') no-repeat scroll center top #000",
  'padding-top': "150px"
   });

сейчас фон выводится но при обновление страницы он не меняется как сделать чтобы фон менялся на другую картинку и соответственно менялись ссылки
на пример картинка 1 ссылка 1 обновляем страницу картинка 2 ссылка 2

рони 14.05.2016 11:39

Николай_777,
накидайте массив ссылок на картинки


Часовой пояс GMT +3, время: 12:08.