Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Подсвечивание активного сейчас пункта меню (https://javascript.ru/forum/dom-window/60336-podsvechivanie-aktivnogo-sejjchas-punkta-menyu.html)

dpts 23.12.2015 11:59

Подсвечивание активного сейчас пункта меню
 
День добрый.
Есть вот такая разметка
Код:

<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <meta http-equiv="Content-Language" content="ru">
  <title>test</title>
  <style>
  body{
      font-family: Verdana, Geneva, sans-serif;
  }

  .one-section{
    display: inline-block;
    position: relative;
    margin: 10px;
    margin-top: 20px;
    padding: 10px;
    padding-left: 20px;
    padding-right: 20px;
    background: none;
    color: #000000;
    border: 1px dotted #3366FF;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    width: 94%;
    height: auto;
}
.os-head{
  color: #3366FF;
  line-height: 20px;
  background: white;
  padding-left: 10px;
  padding-right: 10px;
  font-size: 16px;
  font-weight: bold;
  position: relative;
  left: -10px;
  top:-22px;
  display: inline;
  width: content;
  z-index: 100;
}
.os-content{
  background: none;
  border: 0px none;
  position: relative;
  display: block;
  top: -10px;
  height: auto;
}
.os-section-name{
    width: auto;
    line-height: 40px;
    font-weight: bold;
    letter-spacing: 1px;
    color: #3366FF;
    font-size: 18px;
    margin: 0px 20px;
    padding: 0px;
    display: inline;
}
.os-setting-link{
    color: #3366FF;
    text-decoration: none;
}
.os-settings-li {
        text-decoration: none;
        line-height: 30px;
        background: #ffffff;
        list-style-type: none;
        text-transform: capitalize;
        margin-left: 10px;
    margin-bottom: 10px;
    margin-top: 5px;
        padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
    border-left: 4px solid rgba(102,0,255,0.05);
}

.os-settings-li:hover {
        background: rgba(153, 204, 255, 0.1);
    text-transform: Uppercase;
        font-weight: bold;
}
.maintbl{
    width: 100%;
    border-collapse: collapse;
    border: 0px none;
}
.tdleft{
    width: 20%;
    height: 100%;
    border-left: 0px none;
    border-top: 0px none;
    border-right: 1px dotted black;
    border-bottom: 0px none;
}
.tdright{
    width: 80%;
    height: 100%;
    border: 0px none;
}
.content{
    background: none;
    width: 98%;
    height: 98%;
}

  </style>
  <script>
  function onoff(num) {
        max=50;

        for(t=1;t<=max;t++) {
            if (t==num) {
                                document.getElementById(t).style.display='';
            }

            else {
            document.getElementById(t).style.display='none';
            }
        }
    }
  </script>
</head>

<body>
  <table class="maintbl">
    <tr>
        <td class="tdleft">
            <a class="os-setting-link" href="javascript:void(0)" onClick="onoff(1);"><li class="os-settings-li">Пункт 1</li></a>
            <a class="os-setting-link" href="javascript:void(0)" onClick="onoff(2);"><li class="os-settings-li">Пункт 2</li></a>
            <a class="os-setting-link" href="javascript:void(0)" onClick="onoff(3);"><li class="os-settings-li">Пункт 3</li></a>
            <a class="os-setting-link" href="javascript:void(0)" onClick="onoff(4);"><li class="os-settings-li">Пункт 4</li></a>
        </td>
        <td class="right">
                    <div class="content" id="1" style="padding-left:7px;padding-top:10px;width: 98%; display: none;">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 1</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="2" style="padding-left:7px;padding-top:10px;width: 98%; display: none;">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 2</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="3" style="padding-left:7px;padding-top:10px;width: 98%; display: none;">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 3</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="4" style="padding-left:7px;padding-top:10px;width: 98%; display: none;">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 4</font></h2></strong></center><br>

                        </div>
                    </div>
        </td>
    </tr>
  </table>
</body>

</html>

То есть в левой половине пункты меню, в правой дивы с содержимым по каждому пункту меню.

Как сделать так, чтобы пункт меню подсвечивался, когда показывается соответствующий ему див с контентом.

То есть если показывается
Код:

<div class="content" id="2"...
, например, то
Код:

<a class="os-setting-link" href="javascript:void(0)" onClick="onoff(2);"><li class="os-settings-li">Пункт 2</li></a>
было бы выделено фоном цветом, и так по каждому пункту.
И чтобы выделен был только соответствующий показываемому диву с контентом пункт?

рони 23.12.2015 12:14

dpts,
странная вёрстка без ul и обычно ссылка в li а не на оборот... если поискать открывашка будет с десяток вариантов того что вы хотите ...

рони 23.12.2015 12:47

Открывашка 241 меню с подсветкой активного пункта
 
dpts,

center font эти теги тоже бы выкинуть ...
<!DOCTYPE HTML>
<html>

<head>
   <meta charset="utf-8">
  <meta http-equiv="Content-Language" content="ru">
  <title>test</title>
  <style>
  body{
      font-family: Verdana, Geneva, sans-serif;
  }

  .one-section{
    display: inline-block;
    position: relative;
    margin: 10px;
    margin-top: 20px;
    padding: 10px;
    padding-left: 20px;
    padding-right: 20px;
    background: none;
    color: #000000;
    border: 1px dotted #3366FF;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    width: 94%;
    height: auto;
}
.os-head{
   color: #3366FF;
   line-height: 20px;
   background: white;
   padding-left: 10px;
   padding-right: 10px;
   font-size: 16px;
   font-weight: bold;
   position: relative;
   left: -10px;
   top:-22px;
   display: inline;
   width: content;
   z-index: 100;
}
.os-content{
   background: none;
   border: 0px none;
   position: relative;
   display: block;
   top: -10px;
   height: auto;
}
.os-section-name{
    width: auto;
    line-height: 40px;
    font-weight: bold;
    letter-spacing: 1px;
    color: #3366FF;
    font-size: 18px;
    margin: 0px 20px;
    padding: 0px;
    display: inline;
}
.os-setting-link{
    color: #3366FF;
    text-decoration: none;
}
.os-settings-li {
	text-decoration: none;
	line-height: 30px;
	background: #ffffff;
	list-style-type: none;
	text-transform: capitalize;
	margin-left: 10px;
    margin-bottom: 10px;
    margin-top: 5px;
	padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
    border-left: 4px solid rgba(102,0,255,0.05);
}

.os-settings-li:hover {
	background: rgba(153, 204, 255, 0.1);
    text-transform: Uppercase;
	font-weight: bold;
}
.maintbl{
    width: 100%;
    border-collapse: collapse;
    border: 0px none;
}
.tdleft{
    width: 20%;
    height: 100%;
    border-left: 0px none;
    border-top: 0px none;
    border-right: 1px dotted black;
    border-bottom: 0px none;
}
.tdright{
    width: 80%;
    height: 100%;
    border: 0px none;
}
.content{
    display: none;
    background: none;
    width: 98%;
    height: 98%;
}
.os-settings-li.show{
  background-color: #FFA500;
}
.content.show{
  display: block;
  padding-left:7px;
  padding-top:10px;
  width: 98%;
}

  </style>
  <script>
   window.addEventListener('DOMContentLoaded', function() {
       var li = document.querySelectorAll('.os-settings-li'),
           div = document.querySelectorAll('.content');
       [].forEach.call(li, function(el, i) {
           el.addEventListener('click', function() {
               [].forEach.call(div, function(d, k) {
                   i != k && (li[k].classList.remove('show'), d.classList.remove('show'));
               });
               el.classList.toggle('show')
               div[i].classList.toggle('show')
           });
       });
   });
  </script>
</head>

<body>
   <table class="maintbl">
    <tr>
        <td class="tdleft">
            <ul>
            <li class="os-settings-li">Пункт 1</li>
            <li class="os-settings-li">Пункт 2</li>
            <li class="os-settings-li">Пункт 3</li>
            <li class="os-settings-li">Пункт 4</li>
            </ul>
        </td>
        <td class="right">
                    <div class="content" id="1" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 1</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="2" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 2</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="3" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 3</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="4" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 4</font></h2></strong></center><br>

                        </div>
                    </div>
        </td>
    </tr>
   </table>


</body>

</html>

dpts 24.12.2015 08:16

Благодарю.
Все отлично работает.

dpts 09.01.2016 10:45

В продолжение
 
А как сделать так, чтобы если вызов страницы происходит с параметром сразу показывался соответствующий раздел.

То-есть допустим, если страница вызывается:
1. settings.htm?view=1 - то сразу показывается
<div class="content" id="1" style=" ">

2. settings.htm?view=2 - то сразу показывается
<div class="content" id="2" style=" ">


и т.д.

Если никакого параметра view не передано, - то автоматом показывается
<div class="content" id="1" style=" ">


и выделяется соответствующий пункт
<li class="os-settings-li">
?

рони 09.01.2016 16:10

dpts, парсить
window.location.search и ставить условие в строку 134 if(тра-та-та) el.classList.toggle('show')

dpts 12.01.2016 08:15

Цитата:

Сообщение от рони (Сообщение 403086)
dpts, парсить
window.location.search и ставить условие в строку 134 if(тра-та-та) el.classList.toggle('show')

Учитывая, что в JS я полнейший ноль, парсить window.location.search - "не ближний свет".
Значение параметра считывается VBS-ом и вполне нормально может быть передано в js.
То есть js-ом надо только показать определенный div и подсветить соответствующий ему li.

рони 12.01.2016 08:43

getParameterByName поиск параметров в location.search
 
dpts,

http://stackoverflow.com/questions/9...-in-javascript
window.addEventListener('DOMContentLoaded', function() {
      function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}


       var view = +getParameterByName('view')||1,
           li = document.querySelectorAll('.os-settings-li'),
           div = document.querySelectorAll('.content');
       [].forEach.call(li, function(el, i) {
           el.addEventListener('click', function() {
               [].forEach.call(div, function(d, k) {
                   i != k && (li[k].classList.remove('show'), d.classList.remove('show'));
               });
               el.classList.toggle('show')
               div[i].classList.toggle('show')
           });
       });
       li[--view].click()
   });

dpts 12.01.2016 09:14

Почти работает
 
window.addEventListener('DOMContentLoaded', function() {
      function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}


       var view = +getParameterByName('view')||1,
           li = document.querySelectorAll('.os-settings-li'),
           div = document.querySelectorAll('.content');
       [].forEach.call(li, function(el, i) {
           el.addEventListener('click', function() {
               [].forEach.call(div, function(d, k) {
                   i != k && (li[k].classList.remove('show'), d.classList.remove('show'));
               });
               el.classList.toggle('show')
               div[i].classList.toggle('show')
           });
       });
       li[--view].click()
       document.getElementById(view+1).style.display='block'
   });


Действительно при загрузке показывает соответствующий див и подсвечивает соответствующий ли.
Но теперь при клике на ЛИ не показывает соответствующий див, не снимает подсветку с ЛИ.

Не было проблемы получить значение из адресной строки, она без проблем берется vbs-ом и условие про есть она или нет проверяется vbs-ом на выходе из vbs-а имеем переменную содержащую цифру 1, 2, 3...n.
Эту переменную я могу скормить javascript-у.
Проблема показать при загрузке соответствующий див+подсветить соответствующий ли+чтобы "переключатель" в предыдущем варианте скрипта продолжал работать.

рони 12.01.2016 09:25

dpts,
зачем строка 23?

dpts 12.01.2016 09:30

А без нее не показывает див - только li подсвечивает.
и при кликах по li - дивы не показывает и подсветку не снимает

рони 12.01.2016 09:44

dpts,
смотрите css и html в 3 посте.

dpts 12.01.2016 09:50

Цитата:

Сообщение от рони (Сообщение 403373)
dpts,
смотрите css и html в 3 посте.

Понял. Сейчас поищу

dpts 12.01.2016 10:01

я дибил.
Нашел. Заработало.

pokk 04.12.2017 07:18

А как сделать, что бы при загрузке странице обработчик click, вызвался и установил в дефолтное положение ?
Дело в том, что по кнопкам у меня:
1) Активизирую input, выбранного меню (см ниже)
2) отправляется get запрос, на получение параметров.(еще не сделал так как застрял на дефолте)


window.addEventListener('DOMContentLoaded', function() {
   var li = document.querySelectorAll('.os-settings-li'),
	   div = document.querySelectorAll('.content');
   [].forEach.call(li, function(el, i) {
	   el.addEventListener('click', function() {
		   [].forEach.call(div, function(d, k) {
			   i != k && (li[k].classList.remove('show'), d.classList.remove('show'));
		   });
		   //------------------------------
		   el.classList.toggle('show')
		   if(div[i].classList=="content"){
			div[i].classList.toggle('show');
		   }
		   //------------------------------
		   var jsonList_all = document.querySelectorAll('.JSON'); //все элементы с json и даже c ACT!!!
		   var jsonList_act = div[i].querySelectorAll('.JSON'); //все элементы внутри div
		   //------------------------------
		   //------Выключить JSON----------
		   //------------------------------
		   //------------------------------
		   for(var k = 0; k < jsonList_all.length; k++){
				jsonList_all[k].classList.remove('act');
		   }
		   //------------------------------
		   for(var k = 0; k < jsonList_act.length; k++){
			if(jsonList_act[k].classList=="JSON"){
				jsonList_act[k].classList.toggle('act');
			}
		   }		   
		   //------------------------------
			<!-- console.log(jsonList_all); -->
			<!-- console.log(jsonList_act); -->
		   //------------------------------
	   });
   });
});


Цитата:

Сообщение от рони (Сообщение 401043)
dpts,

center font эти теги тоже бы выкинуть ...
<!DOCTYPE HTML>
<html>

<head>
   <meta charset="utf-8">
  <meta http-equiv="Content-Language" content="ru">
  <title>test</title>
  <style>
  body{
      font-family: Verdana, Geneva, sans-serif;
  }

  .one-section{
    display: inline-block;
    position: relative;
    margin: 10px;
    margin-top: 20px;
    padding: 10px;
    padding-left: 20px;
    padding-right: 20px;
    background: none;
    color: #000000;
    border: 1px dotted #3366FF;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    width: 94%;
    height: auto;
}
.os-head{
   color: #3366FF;
   line-height: 20px;
   background: white;
   padding-left: 10px;
   padding-right: 10px;
   font-size: 16px;
   font-weight: bold;
   position: relative;
   left: -10px;
   top:-22px;
   display: inline;
   width: content;
   z-index: 100;
}
.os-content{
   background: none;
   border: 0px none;
   position: relative;
   display: block;
   top: -10px;
   height: auto;
}
.os-section-name{
    width: auto;
    line-height: 40px;
    font-weight: bold;
    letter-spacing: 1px;
    color: #3366FF;
    font-size: 18px;
    margin: 0px 20px;
    padding: 0px;
    display: inline;
}
.os-setting-link{
    color: #3366FF;
    text-decoration: none;
}
.os-settings-li {
	text-decoration: none;
	line-height: 30px;
	background: #ffffff;
	list-style-type: none;
	text-transform: capitalize;
	margin-left: 10px;
    margin-bottom: 10px;
    margin-top: 5px;
	padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
    border-left: 4px solid rgba(102,0,255,0.05);
}

.os-settings-li:hover {
	background: rgba(153, 204, 255, 0.1);
    text-transform: Uppercase;
	font-weight: bold;
}
.maintbl{
    width: 100%;
    border-collapse: collapse;
    border: 0px none;
}
.tdleft{
    width: 20%;
    height: 100%;
    border-left: 0px none;
    border-top: 0px none;
    border-right: 1px dotted black;
    border-bottom: 0px none;
}
.tdright{
    width: 80%;
    height: 100%;
    border: 0px none;
}
.content{
    display: none;
    background: none;
    width: 98%;
    height: 98%;
}
.os-settings-li.show{
  background-color: #FFA500;
}
.content.show{
  display: block;
  padding-left:7px;
  padding-top:10px;
  width: 98%;
}

  </style>
  <script>
   window.addEventListener('DOMContentLoaded', function() {
       var li = document.querySelectorAll('.os-settings-li'),
           div = document.querySelectorAll('.content');
       [].forEach.call(li, function(el, i) {
           el.addEventListener('click', function() {
               [].forEach.call(div, function(d, k) {
                   i != k && (li[k].classList.remove('show'), d.classList.remove('show'));
               });
               el.classList.toggle('show')
               div[i].classList.toggle('show')
           });
       });
   });
  </script>
</head>

<body>
   <table class="maintbl">
    <tr>
        <td class="tdleft">
            <ul>
            <li class="os-settings-li">Пункт 1</li>
            <li class="os-settings-li">Пункт 2</li>
            <li class="os-settings-li">Пункт 3</li>
            <li class="os-settings-li">Пункт 4</li>
            </ul>
        </td>
        <td class="right">
                    <div class="content" id="1" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 1</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="2" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 2</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="3" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 3</font></h2></strong></center><br>

                        </div>
                    </div>
                    <div class="content" id="4" style=" ">
                        <div class="steeldetail_block" id="sdb2">
                            <center><strong><h2><font color="#595959">ПРО&nbsp;ПУНКТ 4</font></h2></strong></center><br>

                        </div>
                    </div>
        </td>
    </tr>
   </table>


</body>

</html>


рони 04.12.2017 09:23

Цитата:

Сообщение от pokk
А как сделать, что бы при загрузке странице обработчик click, вызвался и установил в дефолтное положение ?

строка 134
!i && el.click() });

бред какой-то
Цитата:

Сообщение от pokk
if(jsonList_act[k].classList=="JSON")

есть classList.contains
if(jsonList_act[k].classList.contains("JSON")){

на крайний случай
if(jsonList_act[k].className=="JSON")


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