Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Помогите разобраться в коде! Реализовать светофор (https://javascript.ru/forum/misc/51496-pomogite-razobratsya-v-kode-realizovat-svetofor.html)

Vladimir93 08.11.2014 19:33

Помогите разобраться в коде! Реализовать светофор
 
Доброго времени суток. С javascript не работал, учу Java. Появилась задача написать простой светофор с тремя кнопками(для переключения цветов в ручном режиме) Внизу код, такой вопрос. Когда в функции описываю изменение стиля одного дива- все работает, если я в функции изменяю стили всем дивам - изменяеться только первый...тобиж не работает. Так же в теге скрипт разные реализации методов, пытался решить проблему Что не так? Подскажите что почитать, чтобы разобраться..
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
    <meta charset="UTF-8">
    <title>Светофор</title>
    <link rel="stylesheet" type="text/css" href="Stylesheet.css">
    <script type="text/javascript">
        function red1(){
            var red = document.getElementById('closedred');
            style = red.style;
            style.setProperty()
            var yellow = document.getElementById('closedyellow');
            yellow.className = "yellow";
        }
        function red() {
            $("#closedred"). document.getElementById('closedred').style.background = 'red';
            $("#closedyellow"). document.getElementById('closedyellow').style.background = 'yellow';
            document.getElementById('closedred').style.background = 'red';
            function newfunction (){
                document.getElementById('closedyellow').style.background = 'yellow';
            }
        }
        function yellow() {
            document.getElementById('closedyellow').style.background = 'yellow';
        }
        function green() {
            document.getElementById('closedred').style.background = 'red';
        }

//        var color;
//        function ChangeBackground(color, id)
//        {
//            document.getElementById("id").style.backgroundColor=color;
//        }
//
//        function wechsel(color) {
//
//            if (color == 1) {
//                document.getElementById('container').style.backgroundColor = '#ffffff';
//            }
//
//            if (color == 2) {
//                document.getElementById('container').style.backgroundColor = '#0000ff';
//            }
//
//            if (color == 3) {
//                document.getElementById('container').style.backgroundColor = '#ff0000';
//            }
//        }
//
    function changeDiv (id){
        if (id  == document.getElementById('closedred')){
            document.getElementById('closered').style.background = 'red';
            document.getElementById('closedyellow').style.backgroundColor = 'closedyellow';
            document.getElementById('closedgreen').style.backgroundColor = 'closedgreen';
        }
        if (id == document.getElementById('closedyellow')){
            document.getElementById('closedred').style.backgroundColor = 'closedred';
            document.getElementById('closedyellow').style.backgroundColor = 'yellow';
            document.getElementById('closedgreen').style.backgroundColor = 'closedgreen';
        }
        if (id == document.getElementById('closedgreen')){
            document.getElementById('closered').style.backgroundColor = 'closedred';
            document.getElementById('closedyellow').style.backgroundColor = 'closedyellow';
            document.getElementById('closedgreen').style.backgroundColor = 'green';
        }
    }
    </script>
</head>
<body>

<div align="center" id="closedred">

</div>
<div align="center" id="closedyellow">

</div>
<div align="center" id="closedgreen">

</div>
<input type=button value="Запуск" onclick="ready()">
<table border=1 align=center><tr><td><div class=text3><form>
    <input type=button value="Красный" onClick="changeDiv('closedred')">
    <input type=button value="Желтый" onClick="document.getElementById('closedyellow').style.backgroundColor = 'yellow'">
    <input type=button value="Зеленый" onClick="document.getElementById('closedgreen').style.backgroundColor = 'green'">
</form></div></td></table>


</body>
</html>

#red {
     align-content: center;
     width: 100px;
     height: 100px;
     background: #FF0000;
     -moz-border-radius: 50px;
     -webkit-border-radius: 50px;
     border-radius: 50px;
     border: solid;
 }
#green {
    align-content: center;
    width: 100px;
    height: 100px;
    background:  #00FF00;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: solid;
}
#yellow {
    align-content: center;
    width: 100px;
    height: 100px;
    background:  #FFFF00;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: solid;
}
#closedred {
    align-content: center;
    width: 100px;
    height: 100px;
    background: #FFE4E1;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: solid;
}
#closedgreen {
    align-content: center;
    width: 100px;
    height: 100px;
    background:  #F0FFF0;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: solid;
}
#closedyellow {
    align-content: center;
    width: 100px;
    height: 100px;
    background:  #FFFFE0;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: solid;
}

рони 08.11.2014 19:42

Vladimir93,
кавычки зачем в 33 строке?

Vladimir93 08.11.2014 19:46

ыы трудно ответить, все делал по примерам в интернете..

Vladimir93 08.11.2014 19:47

обратите, пожалуйста винмание на метод changeDiv, почему он не работает?

Safort 08.11.2014 20:00

Омг, первый новичок за последние несколько месяцев, который не спутал JS с Java.

Vladimir93,
Цитата:

обратите, пожалуйста винмание на метод changeDiv, почему он не работает?
Потому, что он сравнивает объект со строкой.
Строки сравниваются по значению, а объекты по ссылке.

Safort 08.11.2014 20:06

function changeDiv (id){
        if (id  == 'closedred'){
            document.getElementById('closered').style.background = 'red';
            document.getElementById('closedyellow').style.backgroundColor = 'closedyellow';
            document.getElementById('closedgreen').style.backgroundColor = 'closedgreen';
        }
        if (id == 'closedyellow'){
            document.getElementById('closedred').style.backgroundColor = 'closedred';
            document.getElementById('closedyellow').style.backgroundColor = 'yellow';
            document.getElementById('closedgreen').style.backgroundColor = 'closedgreen';
        }
        if (id == 'closedgreen'){
            document.getElementById('closered').style.backgroundColor = 'closedred';
            document.getElementById('closedyellow').style.backgroundColor = 'closedyellow';
            document.getElementById('closedgreen').style.backgroundColor = 'green';
        }
    }


А так работает?

рони 08.11.2014 20:11

Vladimir93,
:cray:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
    <meta charset="UTF-8">
    <title>Светофор</title>
  <style type="text/css">
body > div{
    width: 100px;
    height: 100px;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    border: 2px solid  rgb(51, 0, 0);
 }
body.green div:nth-child(3){
   opacity: 1 ;
}

body.yellow div:nth-child(2){
   opacity: 1
}
body.red div:nth-child(1){
   opacity: 1
}

body div:nth-child(3){
   opacity: 0.2;  background: green;
}

body div:nth-child(2){
   opacity: 0.2 ; background: yellow;
}
body div:nth-child(1){
   opacity: 0.2  ; background: red;
}
  </style>
    <script type="text/javascript">
    function changeDiv (name){
           document.body.className = name

    }
    </script>
</head>
<body class="green">

<div align="center" id="closedred">

</div>
<div align="center" id="closedyellow">

</div>
<div align="center" id="closedgreen">

</div>

<table border=1 align=center><tr><td><form>
    <input type=button value="Красный" onClick="changeDiv('red')">
    <input type=button value="Желтый" onClick="changeDiv('yellow')">
    <input type=button value="Зеленый" onClick="changeDiv('green')">
</form></td></tr></table>


</body>
</html>

kostyanet 08.11.2014 21:44

Задача произвольного доступа ставит народ в угол на горох. Между тем логика простая как три копейки: стек. Вся ваша блеать память так устроена, иначе бы х там был произвольный доступ. В случае когда глубина стека равна 1, задача из простой как три копейки вырождается в баян:

Код:

if last_item
  hide/off/shrink/move/down/etc last_item
show/on/grow/up/etc current_item
last_item = current_item

Применительно к любому количеству в любом контексте.

Да-да, я про "проффесоров", один все методы в кубе перечислил, другой в порядок привел все формы. Копипаста рулит.

рони 08.11.2014 22:14

kostyanet, доступный перевод вашего сообщения
:-?
Цитата:

в переменной old всегда находится элемент открытый в прошлый раз - перед открытием нового элемента -- элемент в old скрывается -- в него записывается новый и новый old открывается - так понятнее?
http://javascript.ru/forum/events/51...tml#post337992
http://javascript.ru/forum/dom-windo...tml#post271084

kostyanet 08.11.2014 22:44

old блеать, how old? А тот который сейчас небось new? Вот такие переводчики и снабжают нацию технической документацией. Ну и почему у вас БД светофора тогда оказалась в стилях?


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