简体   繁体   中英

JavaScript style div based on another div's style [help]

why does this not work? I want to click a button to show the "nav", and then if the "nav" is blocked the "move" will be text-aligned to center.

I know I could just textAlign it the "move" with the same button, but that is not what I'm looking for.

 const btn = document.getElementById('btn'); const nav = document.getElementById('nav'); const move = document.getElementById('move'); btn.addEventListener('click', () => { if (nav.style.display === "none") { nav.style.display = "block"; } else { nav.style.display = "none"; } }); if (nav.style.display === "block") { move.style.textAlign = "center"; } 
 #nav { background-color: lightblue; display: none; } li { display: inline; } 
 <div id="nav"> <li>one</li> <li>two</li> <li>three</li> </div> <div id="move"> <h4>Hello</h4> </div> <button id="btn">change</button> 

Try to use, in this way you force the text inside #nav to be aligned in the center.

#nav {
  background-color: lightblue;
  display: none;
  text-align: center;
 }

If you need to change the inline style dynamically based on some condition in javascript you could consider looking at the inline style of your dom node using style property ex: nav.style.display

A simple example:

if (nav.style.display === "none") {
    nav.style.display = "block";
    move.style.textAlign = "center";
  } else {
    nav.style.display = "none";
  }

More info on style property can be found here .

const btn = document.getElementById('btn');
const nav = document.getElementById('nav');
const move = document.getElementById('move');

const btn = document.getElementById('btn');
const nav = document.getElementById('nav');
const move = document.getElementById('move');

btn.addEventListener('click', () => {
  if (nav.style.display === "none") {
    nav.style.display = "block";
    move.style.textAlign = "center";
  } else {
    nav.style.display = "none";
  }
});

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