简体   繁体   中英

How to change the content of a div by another div according to a click

I would like to know how to change the content of a div when I click on the menu

Currently it looks like this : 在此处输入图片说明

There is my css and html code :

 body { background-color: #555657; margin: 20px; } /* CADRE PARENT */ #global {} /* CADRE 1 */ #cadre1 { float: left; width: 250px; } #cadre1 span { color: #33A7FF; } /* CADRE 2 */ #cadre2 { color: #2370AB; } #menu, #menu ul { padding: 0; margin: 0; list-style: none; text-align: center; } #menu li { display: block; position: relative; background-color: #2370AB; } #menu li ul li { background-color: white; text-align: center; } #menu ul li { display: inherit; border-radius: 0; } #menu ul li:hover { border-radius: 0; } #menu ul li:last-child { border-radius: 0 0 8px 8px; } #menu ul { position: absolute; z-index: 1000; max-height: 0; left: 0; right: 0; overflow: hidden; -moz-transition: .8s all .3s; -webkit-transition: .8s all .3s; transition: .8s all .3s; } #menu li:hover ul { max-height: 15em; } #menu a { display: block; padding: 8px 32px; color: #fff; } #menu ul a { padding: 8px 0; } #menu li:hover a, #menu li li:hover a { color: #000; } /* CADRE 3 */ #div_profil { display: block; height: 625px; background-color: white; overflow: auto; } #div_experience { display: none; height: 625px; background-color: white; overflow: auto; } #div_projet { display: none; height: 625px; background-color: white; overflow: auto; } #div_contact { display: none; height: 625px; background-color: white; overflow: auto; } /* FOOTER */ #footer { position: fixed; bottom: 20px; background-color: #2370AB; text-align: center; } 
 <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8" /> <title>portfolio FIEVEZ Clément</title> <link type="text/css" rel="stylesheet" href="boostrap/css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <!--CADRE PRINCIPAL--> <div class="row" id="global"> <!--INFO BASIQUE--> <div class="col-sm-3" id="cadre1"> <img src="images/myAvatar.png" alt="avatar" id="avatar" /> <p><span>Nom :</span> FIEVEZ</p> <p><span>Prénom :</span> Clément (René)</p> <p><span>Date de naissance / Age :</span> né le 22 janvier 1996, 22ans</p> <p><span>Lieu de naissance :</span> DENAIN (059)</p> <p><span>Adresse :</span> 85 rue magenta, 53000 LAVAL</p> </div> <!--MENU--> <div class="col-sm-3" id="cadre2"> <ul id="menu"> <li><a href="#Profil">Profil</a> </li> <li><a id="btn_experience" href="#Experience">Expérience</a> </li> <li><a href="#Projets">Projets</a> <ul> <li><a href="#Projet1">Projet 1</a></li> <li><a href="#Projet2">Projet 2</a></li> <li><a href="#Projet3">Projet 3</a></li> <li><a href="#Projet4">projet 4</a></li> </ul> </li> <li><a href="#Contact">Contact</a> </li> </ul> </div> <!--CADRE CHANGEANT--> <div class="col-sm-5" id="div_profil"> <p>Et Epigonus quidem amictu tenus philosophus, ut apparuit, prece frustra temptata, sulcatis lateribus mortisque metu admoto turpi confessione cogitatorum socium, quae nulla erant, fuisse firmavit cum nec vidisset quicquam nec audisset penitus expers forensium rerum; Eusebius vero obiecta fidentius negans, suspensus in eodem gradu constantiae stetit latrocinium illud esse, non iudicium clamans. </p> </div> <div class="col-sm-5" id="div_experience"> <p>div experience</p> </div> <div class="col-sm-5" id="div_projet"> <p>div projet</p> </div> <div class="col-sm-5" id="div_contact"> <p>div contact</p> </div> </div> <footer class="col-sm-12" id="footer"> <div> <p class="copyright">Tout droit reservé. FIEVEZ Corps.</p> </div> </footer> <script type="text/javascript" src="javascript/script.js"></script> </body> </html> 

I would like that when I click on one of the tabs of the menu, the div displayed be replaced by another div.

I tried to use some javascript code but this doesn't work.

What should I use to achieve what I want?

Thanks for your reply, have a good day.

  <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8" /> <title>portfolio FIEVEZ Clément</title> <link type="text/css" rel="stylesheet" href="boostrap/css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css"/> <style> body{ background-color: #555657; margin: 20px; } /* CADRE PARENT */ #global{ } /* CADRE 1 */ #cadre1{ float: left; width: 250px; } #cadre1 span{ color : #33A7FF; } /* CADRE 2 */ #cadre2{ color : #2370AB; } #menu, #menu ul{ padding:0; margin:0; list-style:none; text-align:center; } #menu li{ display:block; position:relative; background-color: #2370AB; } #menu li ul li{ background-color: white; text-align:center; } #menu ul li{ display:inherit; border-radius:0; } #menu ul li:hover{ border-radius:0; } #menu ul li:last-child{ border-radius:0 0 8px 8px; } #menu ul{ position:absolute; z-index: 1000; max-height:0; left: 0; right: 0; overflow:hidden; -moz-transition: .8s all .3s; -webkit-transition: .8s all .3s; transition: .8s all .3s; } #menu li:hover ul{ max-height:15em; } #menu a{ display:block; padding:8px 32px; color:#fff; } #menu ul a{ padding:8px 0; } #menu li:hover a, #menu li li:hover a{ color:#000; } /* CADRE 3 */ #div_profil{ display: block; height: 625px; background-color : white; overflow: auto; } #div_experience{ display: none; height: 625px; background-color : white; overflow: auto; } #div_projet{ display: none; height: 625px; background-color : white; overflow: auto; } #div_contact{ display: none; height: 625px; background-color : white; overflow: auto; } /* FOOTER */ #footer{ position: fixed; bottom: 20px; background-color: #2370AB; text-align: center; } </style> </head> <body> <!--CADRE PRINCIPAL--> <div class="row" id="global"> <!--INFO BASIQUE--> <div class="col-sm-3" id="cadre1"> <img src="images/myAvatar.png" alt="avatar" id="avatar"/> <p><span>Nom :</span> FIEVEZ</p> <p><span>Prénom :</span> Clément (René)</p> <p><span>Date de naissance / Age :</span> né le 22 janvier 1996, 22ans</p> <p><span>Lieu de naissance :</span> DENAIN (059)</p> <p><span>Adresse :</span> 85 rue magenta, 53000 LAVAL</p> </div> <!--MENU--> <div class="col-sm-3" id="cadre2"> <ul id="menu"> <li><a href="#Profil" onclick="div2('div_profil')">Profil</a> </li> <li><a id="btn_experience" href="#Experience" onclick="div2('div_experience')">Expérience</a> </li> <li><a href="#Projets" onclick="div2('div_projet')">Projets</a> <ul> <li><a href="#Projet1">Projet 1</a></li> <li><a href="#Projet2">Projet 2</a></li> <li><a href="#Projet3">Projet 3</a></li> <li><a href="#Projet4">projet 4</a></li> </ul> </li> <li><a href="#Contact" onclick="div2('div_contact')">Contact</a> </li> </ul> </div> <!--CADRE CHANGEANT--> <div class="col-sm-5" id="div_profil" > <p>Et Epigonus quidem amictu tenus philosophus, ut apparuit, prece frustra temptata, sulcatis lateribus mortisque metu admoto turpi confessione cogitatorum socium, quae nulla erant, fuisse firmavit cum nec vidisset quicquam nec audisset penitus expers forensium rerum; Eusebius vero obiecta fidentius negans, suspensus in eodem gradu constantiae stetit latrocinium illud esse, non iudicium clamans. </p> </div> <div class="col-sm-5" id="div_experience"> <p>div experience</p> </div> <div class="col-sm-5" id="div_projet"> <p>div projet</p> </div> <div class="col-sm-5" id="div_contact"> <p>div contact</p> </div> </div> <footer class="col-sm-12" id="footer"> <div> <p class="copyright">Tout droit reservé. FIEVEZ Corps.</p> </div> </footer> <script> function div2(name) { document.getElementById("div_profil").style.display="none"; document.getElementById("div_experience").style.display="none"; document.getElementById("div_projet").style.display="none"; document.getElementById("div_contact").style.display="none"; document.getElementById(name).style.display="block"; } </script> </body> </html> 

Here a quick answer I made up... jsfiddle

HTML

    <a id='1' onclick='myFunction("1");'>Click me 1</a><br/>
    <a id='2' onclick='myFunction("2");'>Click me 2</a><br/>
    <a id='3' onclick='myFunction("3");'>Click me 3</a><br/>
    <a id='4' onclick='myFunction("4");'>Click me 4</a><br/>
    <div id='addText'>
    </div>

Javascript

<script>
function myFunction(id){
  x = document.getElementById("addText");
  if(id == 1){
    x.innerHTML = 'Hello'
    x.style.color = "red";
  } else if(id == 2){
    x.innerHTML = 'Hi'
    x.style.color = "red";
  } else if(id ==3){
    x.innerHTML = 'Option 3'
    x.style.color = "red";
  }else{
    x.innerHTML = 'Goodbye'
    x.style.color = "red";
  }
}

</script>

I left all the styling for you, if you dont plan on having many options this solution will work fine.

You could avoid to use Javascript and try a pure css approach using the :target pseudoclass

As you can see, all the content is already inside the document and the main functionality is preserved even if you don't rely on Javascript and /or CSS (without them the page would still work, thanks to the navigation links with a fragment identifier as their href attributes.

Codepen demo


Markup

<nav role="complementary">
    <ul role="tablist">
      <li role="tab" aria-controls="cnt1" id="tab1" aria-selected="true">
          <a href="#cnt1">Content 1</a></li>
      <li role="tab" aria-controls="cnt2" id="tab2" aria-selected="false">
          <a href="#cnt2">Content 2</a></li>
      <li role="tab" aria-controls="cnt3" id="tab3" aria-selected="false">
          <a href="#cnt3">Content 3</a></li>
      <li role="tab" aria-controls="cnt4" id="tab4" aria-selected="false">
          <a href="#cnt4">Content 4</a></li>
    </ul>
</nav>

<main>
   <section id="cnt1" aria-hidden="false" role="tabpanel" aria-labelledby="tab1">
     <h2>Content 1</h2> 
     <p>This is a lorem ipsum</p>
   </section>
   <section id="cnt2" aria-hidden="true" role="tabpanel" aria-labelledby="tab2">
     <h2>Content 2</h2>   
     <p>I am the content of link #2</p>
   </section>
   <section id="cnt3" aria-hidden="true" role="tabpanel" aria-labelledby="tab3">
     <h2>Content 3</h2>    
     <p>Here's another content</p>
   </section>
   <section id="cnt4" aria-hidden="true" role="tabpanel" aria-labelledby="tab4">
     <h2>Content 4</h2>    
     <p>And that's all folks!</p>
   </section>

</main>

CSS (relevant)

body { display: flex; }

main { 
  flex: 1; 
  align-self: stretch; 
  position: relative; }

ul  { list-style: none; }

nav { align-self: flex-start; }

[role="tabpanel"] {
  position: absolute;
  transition: .25s opacity;
  background: #fff;
  padding: 0 20px;
  left: 0; right: 0; top: 0; bottom: 0;
  opacity: 0; }

[role="tabpanel"]:first-of-type { opacity: .99; }
[role="tabpanel"]:target { opacity: 1; }

With a simple CSS transition you can switch the content appearance.

Note that I've inserted some role and aria-* attributes: in fact this kind of navigation is really close to a tab/tabpanels widget.

Even if javascript is not used here, it could help a lot anyway to increase the accessibility of the content : eg you could attach a transitionend event, detect the visible section (just look at its opacity value) and change some aria-* attributes so to make the life easier for people who use assistive technology.

Javascript
( only for accessibility purpose )

var _gcs = window.getComputedStyle;
var _sections = document.querySelectorAll('[role="tabpanel"]');
var _tabs = document.querySelectorAll('[role="tab"]');

var _setARIAAttributes = () => {
  var currentHash;

  /* set aria-hidden on panels */
  [..._sections].forEach( ( s ) => {
        var hidden = +( _gcs( s ).getPropertyValue( 'opacity' ) ) < 1;
        s.setAttribute( 'aria-hidden', hidden);  
        if (!hidden) currentHash = s.id;
  }); 

  /* set aria-controls on tabs */
  [..._tabs].forEach( ( t ) => {
        var selected = t.getAttribute( 'aria-controls' ) === currentHash;
        t.setAttribute( 'aria-selected', selected );  
  }); 
}

if (!!location.hash) { _setARIAAttributes() }
window.addEventListener('transitionend', () => { _setARIAAttributes(); });

You almost there, now you need to add some flag related to any container div with any link that should point to corresponding div, so eg:

// if you have you markup html with multiple links try this

<ul>
<li><a href="#whatever" data-url="div_profile">My Profile</a></li>
<li><a href="#whatever2" data-url="div_experience">My Experience</a></li>
</ul>

<div>
<div class="content active" id="div_profile">Show you profile here</div>
<div class="content" id="div_experience">Show your experience here</div>
</div>

So then you need to add some JS code to do the trick, this code will do the trick

 var links = document.getElementById('menu').getElementsByTagName('a'); var lastShownDiv = getActiveDiv(); for(var i = 0; i < links.length; i++) { var currentLink = links[i]; currentLink.addEventListener('click', function(event){ var link = this; var targetDiv = link.getAttribute('data-url'); if (lastShownDiv) { removeClassName(lastShownDiv, 'active'); } lastShownDiv = document.getElementById(targetDiv); addClassName(lastShownDiv, 'active'); }, false); } function addClassName(element, classname) { if (!element) { return; } var classlists = element.className.split(' '); classlists.push(classname); element.className = classlists.join(' '); } function removeClassName(element, classname) { if (!element) { return; } var classlists = element.className.split(' '); var indexOfClassName = classlists.indexOf(classname); if (indexOfClassName > -1) { classlists.splice(indexOfClassName, 1); } element.className = classlists.join(' '); } function getActiveDiv() { var actives = document.getElementsByClassName('active'); for(var i = 0; i < actives.length; i++) { return actives[i]; } } 
 body { background-color: #555657; margin: 20px; } /* CADRE PARENT */ #global {} /* CADRE 1 */ #cadre1 { float: left; width: 250px; } #cadre1 span { color: #33A7FF; } /* CADRE 2 */ #cadre2 { color: #2370AB; } #menu, #menu ul { padding: 0; margin: 0; list-style: none; text-align: center; } #menu li { display: block; position: relative; background-color: #2370AB; } #menu li ul li { background-color: white; text-align: center; } #menu ul li { display: inherit; border-radius: 0; } #menu ul li:hover { border-radius: 0; } #menu ul li:last-child { border-radius: 0 0 8px 8px; } #menu ul { position: absolute; z-index: 1000; max-height: 0; left: 0; right: 0; overflow: hidden; -moz-transition: .8s all .3s; -webkit-transition: .8s all .3s; transition: .8s all .3s; } #menu li:hover ul { max-height: 15em; } #menu a { display: block; padding: 8px 32px; color: #fff; } #menu ul a { padding: 8px 0; } #menu li:hover a, #menu li li:hover a { color: #000; } /* CADRE 3 */ .content { display: none; } .content.active { display: block; } #div_profil { height: 625px; background-color: white; overflow: auto; } #div_experience { height: 625px; background-color: white; overflow: auto; } #div_projet { height: 625px; background-color: white; overflow: auto; } #div_contact { height: 625px; background-color: white; overflow: auto; } /* FOOTER */ #footer { position: fixed; bottom: 20px; background-color: #2370AB; text-align: center; } 
 <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8" /> <title>portfolio FIEVEZ Clément</title> <link type="text/css" rel="stylesheet" href="boostrap/css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <!--CADRE PRINCIPAL--> <div class="row" id="global"> <!--INFO BASIQUE--> <div class="col-sm-3" id="cadre1"> <img src="images/myAvatar.png" alt="avatar" id="avatar" /> <p><span>Nom :</span> FIEVEZ</p> <p><span>Prénom :</span> Clément (René)</p> <p><span>Date de naissance / Age :</span> né le 22 janvier 1996, 22ans</p> <p><span>Lieu de naissance :</span> DENAIN (059)</p> <p><span>Adresse :</span> 85 rue magenta, 53000 LAVAL</p> </div> <!--MENU--> <div class="col-sm-3" id="cadre2"> <ul id="menu"> <li><a href="#Profil" data-url="div_profil">Profil</a> </li> <li><a id="btn_experience" href="#Experience" data-url="div_experience">Expérience</a> </li> <li><a href="#Projets" data-url="div_projet">Projets</a> <ul> <li><a href="#Projet1">Projet 1</a></li> <li><a href="#Projet2">Projet 2</a></li> <li><a href="#Projet3">Projet 3</a></li> <li><a href="#Projet4">projet 4</a></li> </ul> </li> <li><a href="#Contact" data-url="div_contact">Contact</a> </li> </ul> </div> <!--CADRE CHANGEANT--> <div class="col-sm-5 content active" id="div_profil"> <p>Et Epigonus quidem amictu tenus philosophus, ut apparuit, prece frustra temptata, sulcatis lateribus mortisque metu admoto turpi confessione cogitatorum socium, quae nulla erant, fuisse firmavit cum nec vidisset quicquam nec audisset penitus expers forensium rerum; Eusebius vero obiecta fidentius negans, suspensus in eodem gradu constantiae stetit latrocinium illud esse, non iudicium clamans. </p> </div> <div class="col-sm-5 content" id="div_experience"> <p>div experience</p> </div> <div class="col-sm-5 content" id="div_projet"> <p>div projet</p> </div> <div class="col-sm-5 content" id="div_contact"> <p>div contact</p> </div> </div> <footer class="col-sm-12 content" id="footer"> <div> <p class="copyright">Tout droit reservé. FIEVEZ Corps.</p> </div> </footer> </body> </html> 

The code above, is your code with some updates, I hope this help you to solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM