2016-09-15 76 views
0

所以我叫時,使元素可見的功能上:切換知名度與點擊原始元素或其他元素

function toggle_visibility(id) { 
 
    var e = document.getElementById(id); 
 
    if (e.style.display == 'block') 
 
    e.style.display = 'none'; 
 
    else 
 
    e.style.display = 'block'; 
 
}
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a> 
 
<a class="url" id="first" href="#">First</a> 
 
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a> 
 
<a class="url" id="second" href="#">Second</a>

而且這樣的作品,但我想是的元素來關閉,如果我使用不同的ID功能。因此,如果我先切換#first,然後再切換#second,我希望#first切換關閉。

回答

0

試試這個:

var lastId = null; 
 
function toggle_visibility(id) { 
 
     if (lastId && id != lastId) { 
 
      var lastEl = document.getElementById(lastId); 
 
      lastEl.style.display = 'none'; 
 
     } 
 
     lastId = id; 
 
     var e = document.getElementById(id); 
 
     if(e.style.display == 'block') 
 
     e.style.display = 'none'; 
 
     else 
 
     e.style.display = 'block'; 
 
     }
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a> 
 
<a class="url" style='display:block' id="first" href="#">First</a> 
 
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a> 
 
<a class="url" style='display:block' id="second" href="#">Second</a>

+0

工作太棒了!謝謝 –

0

這是一個可能的解決方案。

 function toggle_visibility(id) { 
 
      if (id=='first'){ 
 
       var e = document.getElementById(id); 
 
       var f = document.getElementById('second'); 
 
       } 
 
     else {var e = document.getElementById(id); 
 
       var f = document.getElementById('first');} 
 
       if(e.style.display == 'block'){ 
 
       e.style.display = 'none'; 
 
       f.style.display= 'block';} 
 
     
 
       else 
 
       { e.style.display = 'block'; 
 
       f.style.display = 'none';} 
 
       }
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a> 
 
    <a class="url" id="first" href="#">First</a> 
 
    <a class="button" href="#" onclick="toggle_visibility('second');">Button2</a> 
 
    <a class="url" id="second" href="#">Second</a>

0

你可以試試這個

toggle_visibility = function(id) { 
 
    var all_urls = document.getElementsByClassName('url'); 
 
    var e = document.getElementById(id); 
 
    for(var i=0;i<all_urls.length;i++){ 
 
     if(all_urls[i].id !== id) 
 
     all_urls[i].style.display= 'none'; 
 
    } 
 
    if(e.style.display == 'block') 
 
     e.style.display = 'none'; 
 
    else 
 
     e.style.display = 'block'; 
 
}
<a class="button" href="#" onclick="toggle_visibility('first');">Button</a> 
 
<a class="url" id="first" href="#">First</a> 
 
<a class="button" href="#" onclick="toggle_visibility('second');">Button2</a> 
 
<a class="url" id="second" href="#">Second</a>

+0

工作很好!謝謝 –