Javascript (НЕТ JQUERY) Toggle Div - PullRequest
1 голос
/ 14 марта 2019

Я пытаюсь переключать несколько делений с помощью карты изображений.Моя конечная цель:

  1. Начать со всех скрытых div
  2. Нажмите на div, чтобы переключиться и показать
  3. Нажмите на другой div, чтобы отобразить второйdiv, но скрыть все остальные div
  4. Нажмите последний выбранный div, чтобы скрыть div

Я очень новичок в Javascript.Буквально у меня ушло навсегда, просто чтобы понять, как даже создать функцию для переключения.Я НЕ МОГУ ИСПОЛЬЗОВАТЬ JQUERY, поэтому, пожалуйста, не предлагайте никаких решений, требующих от меня использования этой библиотеки.

function toggle(id) {
  var x = document.getElementById(id)
  if(x.style.display =='none')
    x.style.display = 'block';
  else x.style.display = 'none'; 
}
<img id="Image-Maps-Com-image-maps-2019-03-13-221105" src="https://picsum.photos/349/290" border="0" width="349" height="290" orgWidth="349" orgHeight="290" usemap="#image-maps-2019-03-13-221105" alt="" />
<map name="image-maps-2019-03-13-221105" id="ImageMapsCom-image-maps-2019-03-13-221105">
<area alt="" title="" href="#" onclick="toggle('unit1')" shape="rect" coords="9,164,152,263" style="outline:none;" target="_self" />
<area alt="" title="" href="#" onclick="toggle('unit2')" shape="rect" coords="198,175,328,273" style="outline:none;" target="_self" />
<area alt="" title="" href="#" onclick="toggle('unit3')" shape="rect" coords="55,25,291,132" style="outline:none;" target="_self" />
<area shape="rect" coords="347,288,349,290" alt="Image Map" style="outline:none;" title="image Map" href="http://www.image-maps.com/index.php?aff=mapped_users_0" />
</map>

<div id="unit1" class="unit1" style="display: none;">
Hello World
</div>

<div id="unit2" class="unit2" style="display: none;">
This is me
</div>

<div id="unit3" class="unit3" style="display: none;">
Goodbye
</div>

Ответы [ 2 ]

1 голос
/ 14 марта 2019

Вы можете добиться этого, выполнив следующие действия.

  1. Сначала вы должны иметь одинаковые class для всех ваших дивов
  2. Использовать querySelectorAll() и скрывать все элементы класса
  3. Затем вы переключаете требуемый id с помощью троичного оператора.
  4. Вы должны получить все <area> и использовать addEventListener() вместо onclick = toggle(...)

document.querySelectorAll('area[alt]').forEach((a,i) =>
{
   a.addEventListener('click',(e) => {
    e.preventDefault();
    var x = document.getElementById(`unit${i+1}`)  
    let {display} = x.style
    document.querySelectorAll('.unit').forEach(z => z.style.display = 'none')
    x.style.display = display === 'none' ? 'block' : 'none';
   })
})
<img id="Image-Maps-Com-image-maps-2019-03-13-221105" src="https://picsum.photos/349/290" border="0" width="349" height="290" orgWidth="349" orgHeight="290" usemap="#image-maps-2019-03-13-221105" alt="" />
<map name="image-maps-2019-03-13-221105" id="ImageMapsCom-image-maps-2019-03-13-221105">
<area alt="" title="" href="#" shape="rect" coords="9,164,152,263" style="outline:none;" target="_self" />
<area alt="" title="" href="#"  shape="rect" coords="198,175,328,273" style="outline:none;" target="_self" />
<area alt="" title="" href="#"  shape="rect" coords="55,25,291,132" style="outline:none;" target="_self" />
<area shape="rect" coords="347,288,349,290" alt="Image Map" style="outline:none;" title="image Map" href="http://www.image-maps.com/index.php?aff=mapped_users_0" />
</map>

<div id="unit1" class="unit" style="display: none;">
Hello World
</div>

<div id="unit2" class="unit" style="display: none;">
This is me
</div>

<div id="unit3" class="unit" style="display: none;">
Goodbye
</div>
0 голосов
/ 14 марта 2019

1) Get новый статус для единицы, которую вы щелкнули.

2) Set дисплей: нет для всех устройств.

3) Set новый статус для единицы, на которую вы нажали.

function toggle(id) {
  var x = document.getElementById(id) ;
  var newStatus = (x.style.display === 'none') ? 'block' : 'none' ;
  var units = document.getElementsByClassName('units') ;
  for( var i = 0; i < units.length ; i++ ) 
    units[i].style.display = 'none'
  x.style.display = newStatus ;
}
<img id="Image-Maps-Com-image-maps-2019-03-13-221105" src="https://picsum.photos/349/290" border="0" width="349" height="290" orgWidth="349" orgHeight="290" usemap="#image-maps-2019-03-13-221105" alt="" />
<map name="image-maps-2019-03-13-221105" id="ImageMapsCom-image-maps-2019-03-13-221105">
<area alt="" title="" href="#" onclick="toggle('unit1')" shape="rect" coords="9,164,152,263" style="outline:none;" target="_self" />
<area alt="" title="" href="#" onclick="toggle('unit2')" shape="rect" coords="198,175,328,273" style="outline:none;" target="_self" />
<area alt="" title="" href="#" onclick="toggle('unit3')" shape="rect" coords="55,25,291,132" style="outline:none;" target="_self" />
<area shape="rect" coords="347,288,349,290" alt="Image Map" style="outline:none;" title="image Map" href="http://www.image-maps.com/index.php?aff=mapped_users_0" />
</map>

<div id="unit1" class="units unit1" style="display: none;">
Hello World
</div>

<div id="unit2" class="units unit2" style="display: none;">
This is me
</div>

<div id="unit3" class="units unit3" style="display: none;">
Goodbye
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...