简体   繁体   中英

Turn if/else statement into ternary operator

How would you turn this if else statement into ternary operator? I know it would read better with an if else statement, I'm just curious

Thank you.

if (window.scrollY > 200) {
        header.style.padding= "5rem";
        header.style.boxShadow="0 0.4px 10px 1px #999";
    } else {
        header.style.padding= "1rem";
        header.style.boxShadow="none";
        })
    }

It's pretty trivial...

header.style.padding = window.scrollY > 200
  ? "5rem"
  : "1rem";
header.style.boxShadow = window.scrollY > 200
  ? "0 0.4px 10px 1px #999"
  : 'none';

But rather than setting these manually with JavaScript (using the conditional operator or anything else), consider toggling CSS classes instead, eg

.header {
  padding: 1rem;
  box-shadow: 'none';
}
.header.scrolled {
  padding: 5rem;
  box-shadow: 0 0.4px 10px 1px #999;
}
header.classList.toggle('scrolled', window.scrollY > 200);
if (window.scrollY > 200) {
    header.style.padding= "5rem";
    header.style.boxShadow="0 0.4px 10px 1px #999";
} else {
    header.style.padding= "1rem";
    header.style.boxShadow="none";

to ternary

window.scrollY > 200 ?
  ( header.style.padding= "5rem",
    header.style.boxShadow="0 0.4px 10px 1px #999" )
:
  ( header.style.padding= "1rem",
    header.style.boxShadow="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