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,
накидайте массив ссылок на картинки

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

а можно пример если не сложно рабочий

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

а можно по подробнее как это реализовать если не сложно помоги

рони 14.05.2016 11:59

Николай_777,
накидайте массив ссылок на картинки!!! пяток хотябы

рони 14.05.2016 12:01

Николай_777,
["...","..."...]

Николай_777 14.05.2016 12:18

а можешь написать как это будет выглядеть ото я полный ноль в js и куда вставлять это все
<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 -80px #000",
					'padding-top': "20px"
				  
				    
				});

			    
				// добавим ссылки
				jQuery('body').prepend(
					'<a id="ar_t12" style="cursor: pointer; z-index: 1; position: absolute; top: 0px; left: 0px; width: 100%; height: 286px;" 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>

то есть помочь до работать код

рони 14.05.2016 12:30

Николай_777,
вы что такое массив в курсе? :cray: вас просили написать только то что в 1 строке.
var url = ['http://www.top-4f.ru/img/8975.jpg','http://www.top-4f.ru/_ld/0/s58345627.jpg'],
            num = url.length * Math.random()|0;
            url = url[num];
        jQuery('body').css({
          'background': "url('"+url+"') no-repeat scroll center top #000",
          'padding-top': "150px"
        });

Николай_777 14.05.2016 13:01

а как добавить разные ссылки для картинок чтобы когда картинки обновляются у них были разные ссылки то есть когда картинка танки то ссылка на танки если черепашки то ссылка черепашки и еще картинка черепашки цвета вот такого rgb(242, 238, 226)
как сделать чтобы цвет фона был таким же то есть когда появлялась картинка черепашки то фон сайта был таким
padding-top: 150px;
background: url("http://www.top-4f.ru/_ld/0/s58345627.jpg") 50% 0% no-repeat scroll rgb(242, 238, 226);
а когда танки то таким

padding-top: 150px;
background: url("http://www.top-4f.ru/img/8975.jpg") 50% 0% no-repeat scroll rgb(0, 0, 0);

рони 14.05.2016 13:06

Николай_777,
далее сами ...
var url = ['http://www.top-4f.ru/img/8975.jpg','http://www.top-4f.ru/_ld/0/s58345627.jpg'],
            rgb = ['rgb(0, 0, 0)','rgb(242, 238, 226)'],
            num = url.length * Math.random()|0;
            url = url[num];
            rgb = rgb[num];
        jQuery('body').css({
          'background': "url('"+url+"') no-repeat scroll center top " + rgb,
          'padding-top': "150px"
        });

Николай_777 14.05.2016 13:30

помоги еще ссылками пожалуйста давай я тебе на телефон рублей 300 закину за помощь

рони 14.05.2016 14:04

Николай_777,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">

 </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <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;
        /* Брендирование */
        var url = ['http://www.top-4f.ru/img/8975.jpg','http://www.top-4f.ru/_ld/0/s58345627.jpg'],
            rgb = ['rgb(0, 0, 0)','rgb(242, 238, 226)'],
            tt = ['http://','http://'], src = ['http://javascript.ru/forum/images/smilies/unsure.gif','http://javascript.ru/forum/images/smilies/dance3.gif'], ttext = ["aaaa","cccc"],
            rr = ['http://','http://'], rtext = ["2222","kkkk"],
            ll = ['http://','http://']; ltext = ["tttt","uuuuu"],
            num = url.length * Math.random()|0;
            url = url[num];
            rgb = rgb[num];
            tt = tt[num]; src = src[num]; ttext = ttext[num];
            rr = rr[num]; rtext = rtext[num];
            ll = ll[num]; ltext = ltext[num];

        jQuery('body').css({
          'background': "url('"+url+"') no-repeat scroll center top " + rgb,
          '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="'+tt+'" target="_blank"><img src="'+src+'" width="70" height="70" />'+ttext+'</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="'+rr+'" target="_blank">'+rtext+'</a>'
        );
        jQuery('body').prepend(
          '<a id="ar_l12" style="cursor: pointer; z-index: 1; position: absolute; top: 100px; left: 0px; width: ' + side_width + 'px; height: 850px;" href="'+ll+'" target="_blank">'+ltext+'</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>



</head>

<body>


</body>
</html>


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