Show/hide 'div' folosind JavaScript

Pentru un site, am'm a face, vreau să încarce un div, și ascunde o alta, apoi au două butoane care va comuta opinii între div folosind JavaScript.

Acest lucru este meu actualul cod

function replaceContentInContainer(target, source) {
  document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}

function replaceContentInOtherContainer(replace_target, source) {
  document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;
}
<html>
<button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button>
<button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button>

<div>
  <span id="target">div1</span>
</div>

<div style="display:none">
  <span id="replace_target">div2</span>
</div>

Cea de-a doua funcție care înlocuiește div2 nu este de lucru, dar primul este.

Soluția

Cum pentru a afișa sau a ascunde un element:

În scopul de a afișa sau a ascunde un element, manipula element's stil proprietate. În cele mai multe cazuri, probabil că doriți să modificați elementul's "display" proprietate:

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

Alternativ, dacă doriți totuși elementul pentru a ocupa spațiu (cum ar fi dacă ați fost de a ascunde o celulă de tabel), ai putea schimba element's "vizibilitate" proprietate în schimb:

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

Ascunde o colecție de elemente:

Dacă doriți pentru a ascunde o colecție de elemente, doar repeta peste fiecare element și de a schimba elementul's "afișaj" la "nici unul":

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));
hide(document.querySelectorAll('.target'));

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
<div class="target">This div will be hidden.</div>

<span class="target">This span will be hidden as well.</span>

Arată o colecție de elemente:

Cele mai multe din timp, probabil, va fi comutarea între display: none " și " display: block, ceea ce înseamnă că următoarele poate fi suficiente atunci când arată o colecție de elemente.

Puteți specifica opțional dorit "display" ca al doilea argument, dacă nu't vreau să default la "bloc".

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value
var elements = document.querySelectorAll('.target');

show(elements, 'inline-block'); // The second param allows you to specify a display value

show(document.getElementById('hidden-input'));

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>

<span>Inline span..</span>

<input id="hidden-input" />

Alternativ, o mai bună abordare pentru a arăta elementul(s) ar fi pur și simplu scoateți inline "display" styling pentru a reveni la starea inițială. Apoi verificați calculat "display" stil de element pentru a determina dacă acesta este ascuns de o cascadă regula. Dacă este așa, atunci arată element.

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}
show(document.querySelectorAll('.target'));

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}
<span class="target" style="display: none">Should revert back to being inline.</span>

<span class="target" style="display: none">Inline as well.</span>

<div class="target" style="display: none">Should revert back to being block level.</div>

<span class="target" style="display: none">Should revert back to being inline.</span>

(Dacă doriți să-l ia un pas mai departe, ai putea chiar să imite ceea ce jQuery face și de a determina elementul's browser-ul implicit de styling prin adăugarea la element la un gol iframe (fără un conflict de stil) și apoi a prelua calculat de styling. Procedând astfel, veți cunoaște adevărata inițială "display" proprietate valoarea elementului și nu te vei't trebuie să hardcode o valoare în scopul de a obține rezultatele dorite.)

Comutare de afișare:

În mod similar, dacă doriți pentru a comuta la "display" de un element sau o colecție de elemente, ai putea pur și simplu repeta peste fiecare element și a stabili dacă acesta este vizibil prin verificarea valorii calculate de la "display" de proprietate. Daca's vizibile, setați "afișaj" la "nici unul", în caz contrar, scoateți inline "display" styling, și dacă-l's încă ascunse, setați "display" cu valoarea specificată sau implicit hardcoded, "bloc".

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});
document.getElementById('toggle-button').addEventListener('click', function () {
    toggle(document.querySelectorAll('.target'));
});

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
.target { display: none; }
Toggle display

<span class="target">Toggle the span.</span>

<div class="target">Toggle the div.</div>
Comentarii (0)

Puteți folosi, de asemenea, jQuery JavaScript framework:

Pentru A Ascunde Div Bloc

$(".divIDClass").hide();

Pentru a arăta Div Bloc

$(".divIDClass").show();
Comentarii (5)

Puteți pur și simplu să manipuleze stilul de div în cauză...

document.getElementById('target').style.display = 'none';
Comentarii (1)

Puteți Ascunde/Afișa Div folosind funcția Js. proba de mai jos

<script>
    function showDivAttid(){

        if(Your Condition) {

            document.getElementById("attid").style.display = 'inline';
        }
        else
        {
            document.getElementById("attid").style.display = 'none';
        }
    }

</script>

HTML -

<div  id="attid" style="display:none;">Show/Hide this text</div>
Comentarii (1)

Folosind stilul:


   .hidden {
        display: none;
   {
   .visible {
        display: block;
   }

Folosind un handler de eveniment în JavaScript este mai bună decât onclick="" atribute HTML:

View Portfolio
View Results

<div class="visible" id="portfolio">
    <span>div1</span>
</div>

<div class"hidden" id="results">
    <span>div2</span>
</div>

JavaScript:

<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');
    };

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');
    };

</script>

jQuery poate ajuta să manipuleze elemente DOM ușor!

Comentarii (1)

Am găsit acest simplu cod JavaScript foarte la îndemână!

#<script type="text/javascript">
    function toggle_visibility(id) 
    {
        var e = document.getElementById(id);
        if ( e.style.display == 'block' )
            e.style.display = 'none';
        else
            e.style.display = 'block';
    }
</script>
Comentarii (0)

Set HTML ca

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

Și acum setați javascript ca

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }
Comentarii (0)

Doar Simplu Setați atributul de stil de IDENTITATE:

Pentru a Arăta cele ascunse div

<div id="xyz" style="display:none">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='block';  // to hide

Pentru a ascunde arătat div

<div id="xyz">
     ...............
</div>
//In JavaScript

document.getElementById('xyz').style.display ='none';  // to display
Comentarii (0)
<script type="text/javascript">
    function hide(){
        document.getElementById('id').hidden = true;
    }
    function show(){
        document.getElementById('id').hidden = false;
    }
</script>
Comentarii (1)

Am găsit această întrebare și, recent, am fost de punere în aplicare unele UIs folosind Vue.js deci, acest lucru poate fi o bună alternativă.

Primul cod nu este ascuns "țintă", atunci când faceți clic pe Vizualizare Profil. Sunt imperative conținutul "țintă" cu div2.

let multiple = new Vue({
  el: "#multiple",
  data: {
    items: [{
        id: 0,
        name: 'View Profile',
        desc: 'Show profile',
        show: false,
      },
      {
        id: 1,
        name: 'View Results',
        desc: 'Show results',
        show: false,
      },
    ],
    selected: '',
    shown: false,
  },
  methods: {
    showItem: function(item) {
      if (this.selected && this.selected.id === item.id) {
        item.show = item.show && this.shown ? false : !item.show;
      } else {
        item.show = (this.selected.show || !item.show) && this.shown ? true : !this.shown;
      }
      this.shown = item.show;
      this.selected = item;
    },
  },
});
<div id="multiple">
  {{item.name}}

  <div class="" v-if="shown">: {{selected.desc}}</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
Comentarii (0)

Și Purescript răspuns, pentru persoanele care folosesc cu Halogen:

import CSS (display, displayNone)
import Halogen.HTML as HH
import Halogen.HTML.CSS as CSS

render state = 
  HH.div [ CSS.style $ display displayNone ] [ HH.text "Hi there!" ]

Dacă aveți "inspect element", ar'll vedea ceva de genul:

<div style="display: none">Hi there!</div>

dar de fapt nimic nu se va afișa pe ecran, cum era de așteptat.

Comentarii (0)

Doar Funcția de Simplu Nevoie Pentru a pune în aplicare Show/hide 'div' folosind JavaScript

<a id="morelink" class="link-more" style="font-weight: bold; display: block;" onclick="this.style.display='none'; document.getElementById('states').style.display='block'; return false;">READ MORE</a>

<div id="states" style="display: block; line-height: 1.6em;">
 text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here  
    <a class="link-less" style="font-weight: bold;" onclick="document.getElementById('morelink').style.display='inline-block'; document.getElementById('states').style.display='none'; return false;">LESS INFORMATION</a>
    </div>
Comentarii (0)