Скройте divs onload и заставьте исчезать других по клику - PullRequest
0 голосов
/ 01 июля 2018

Я нашел, как скрыть / показать div на клике, но по умолчанию это показ, и я хотел бы, чтобы они скрывали и отображали только клик. также я хотел бы, чтобы когда кто-то показывал, это заставляло других прятаться.

Вот мой код:

<img id="img1" 
 onclick="document.getElementById ('txt_1').className = document.getElementById ('txt_1').className == 'hidden' ? '' : 'hidden'"
<i>https://codepen.io/drudrudru/pen/KeJQxY</i> 

Ответы [ 2 ]

0 голосов
/ 01 июля 2018

Чтобы скрыть второй текст по умолчанию, вы добавляете класс hidden в свой HTML. Ваш JS удалит его при переключении. Не сильно меняя свою структуру, вот пример, который скроет другой блок текста, когда вы раскроете другой. Это не будет показывать, когда ты прячешься.

Здесь есть повторение кода, которое вы можете улучшить, но это должно помочь вам.

   <p id="txt_1">Born on April 22, 1923, in Nashville, Tennessee, Bettie was the second of Walter Roy Page and Edna Mae Pirtle’s six children. During Bettie’s early years, the Page family traveled around the country ...</p>   


   <p id="txt_2"> I would like to appear on click of "img2" and make "txt_1" disappear (and vice versa)</p>




       <img id="img1" 
 onclick="document.getElementById ('txt_1').className = document.getElementById ('txt_1').className == 'hidden' ? '' : 'hidden'"

 src="https://image.flaticon.com/icons/png/128/124/124563.png">     
  <br>

       <img id="img2" 
 onclick="document.getElementById ('txt_2').className = document.getElementById ('txt_2').className == 'hidden' ? '' : 'hidden'"    
 src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png"> 

function image1Toggle() { 
if (document.getElementById("txt_1").className == "hidden") {
  document.getElementById("txt_1").className = ""; //show
  document.getElementById("txt_2").className = "hidden"; //hide
  
} else {
    document.getElementById("txt_1").className = "hidden"; //hide
}
}


function image2Toggle() { 
if (document.getElementById("txt_2").className == "hidden") {
  document.getElementById("txt_2").className = ""; //show
  document.getElementById("txt_1").className = "hidden"; //hide
  
} else {
    document.getElementById("txt_2").className = "hidden"; //hide
}
}
.hidden {display:none} 

     #txt_1 {color:red;
               position: absolute;
               left:242px;
               width: 26%;
               top:30px;
               z-index: 3;}

#txt_2 {color:green;
               position: absolute;
               left:242px;
               width: 26%;
               top:180px;
               z-index: 3;}

                                                             
   <!--- I would have txt hide onload and appear when the corresponding img is onclick--->

       <p id="txt_1">Born on April 22, 1923, in Nashville, Tennessee, Bettie was the second of Walter Roy Page and Edna Mae Pirtle’s six children. During Bettie’s early years, the Page family traveled around the country ...</p>   


       <p id="txt_2" class="hidden"> I would like to appear on click of "img2" and make "txt_1" disappear (and vice versa)</p>
           
 


           <img id="img1" 
     onclick="image1Toggle()"
     
     src="https://image.flaticon.com/icons/png/128/124/124563.png">     
      <br>

           <img id="img2" 
     onclick="image2Toggle()"    
     src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png"> 
0 голосов
/ 01 июля 2018

Сначала добавьте класс hidden в оба абзаца.

function showHide(obj) {
  var txt1 = document.getElementById ('txt_1'),
      txt2 = document.getElementById ('txt_2')
  if (obj.id === 'img1') {
    txt1.classList.toggle('hidden'); //it'll toggle the hidden class
    txt2.classList.add('hidden'); //it'll add the hidden class to the other paragraph, if its not already hidden
  }
  else {
    txt2.classList.toggle('hidden');
    txt1.classList.add('hidden');
  }
}
.hidden {display:none} 

     #txt_1 {color:red;
               position: absolute;
               left:242px;
               width: 26%;
               top:30px;
               z-index: 3;}

#txt_2 {color:green;
               position: absolute;
               left:242px;
               width: 26%;
               top:180px;
               z-index: 3;}

                                                             
   <!--- I would have txt hide onload and appear when the corresponding img is onclick--->

       <p id="txt_1" class="hidden">Born on April 22, 1923, in Nashville, Tennessee, Bettie was the second of Walter Roy Page and Edna Mae Pirtle’s six children. During Bettie’s early years, the Page family traveled around the country ...</p>   


       <p id="txt_2" class="hidden"> I would like to appear on click of "img2" and make "txt_1" disappear (and vice versa)</p>
           
 


           <img id="img1" 
     onclick="showHide(this);"
     
     src="https://image.flaticon.com/icons/png/128/124/124563.png">     
      <br>

           <img id="img2" 
     onclick="showHide(this);"    
     src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png"> 

Затем вызовите функцию, здесь я ее называю showHide(), в свойстве images onclick. Хорошей практикой является написание кода JavaScript отдельно. Еще лучше, если вы полностью избегаете onclick в этой ситуации Вместо этого используйте прослушиватель событий. Ниже я показываю другой подход с использованием прослушивателя событий.

document.getElementById('img1').addEventListener('click', function(e) {
  showHide(e.target);
});
document.getElementById('img2').addEventListener('click', function(e) {
  showHide(e.target);
});


function showHide(obj) {
  var txt1 = document.getElementById ('txt_1'),
      txt2 = document.getElementById ('txt_2')
  if (obj.id === 'img1') {
    txt1.classList.toggle('hidden'); //it'll toggle the hidden class
    txt2.classList.add('hidden'); //it'll add the hidden class to the other paragraph, if its not already hidden
  }
  else {
    txt2.classList.toggle('hidden');
    txt1.classList.add('hidden');
  }
}
.hidden {display:none} 

     #txt_1 {color:red;
               position: absolute;
               left:242px;
               width: 26%;
               top:30px;
               z-index: 3;}

#txt_2 {color:green;
               position: absolute;
               left:242px;
               width: 26%;
               top:180px;
               z-index: 3;}

                                                             
   <!--- I would have txt hide onload and appear when the corresponding img is onclick--->

       <p id="txt_1" class="hidden">Born on April 22, 1923, in Nashville, Tennessee, Bettie was the second of Walter Roy Page and Edna Mae Pirtle’s six children. During Bettie’s early years, the Page family traveled around the country ...</p>   


       <p id="txt_2" class="hidden"> I would like to appear on click of "img2" and make "txt_1" disappear (and vice versa)</p>
           
 


           <img id="img1" src="https://image.flaticon.com/icons/png/128/124/124563.png">     
      <br>

           <img id="img2" src="https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png"> 
...