简体   繁体   中英

How to add and remove CSS code from classes with pseudo element?

 function toggle(){ var button=document.querySelector('.toggle'); var bar=document.querySelector('.slide'); if(bar.className==='slide up'){ bar.className='slide down'; }else{ bar.className='slide up'; } } 
 *{ margin:0px; padding:0px; height:100%; width:100%; } .box{ overflow:hidden; background-image: url('http://tombricker.smugmug.com/Travel/San-Francisco-California/i-jk2Z7D7/0/L/san-francisco-golden-gate-bridge-morning-sun-bricker-L.jpg'); background-size: cover; background-position:center; } .slide{ position: relative; left:39vw; width: 55vw; height: 75vh; background: red; } .slide:before { content: ''; position:absolute; top:-3vh; width: 0px; height: 0px; border-left:27.5vw solid transparent; border-right:27.5vw solid transparent; border-bottom:3vh solid white; } .slide.down{ transform:translateY(100vh); } .slide.up{ transform:translateY(25vh); } .slide{ transition:transform 0.4s ease-out; } 
 <div class='box'> <div class='slide up' onclick='toggle()'></div> </div> 

The white triangle on top of the red rectangle is made with pseudo element :before. What I am trying to do is when the sliding tag is up, the white triangle should be pointing down. To do that, I want to write a JS code that will add a transform CSS to that class with pseudo element that will translate triangle down by its height and rotate by 180deg.

I find on this developer blog the JS code to add, but it does not work and I don't know how to delete that code when the tag is down.

 function toggle(){ var button=document.querySelector('.toggle'); var bar=document.querySelector('.slide'); if(bar.className==='slide up'){ bar.className='slide down'; //Here is where I need to add the line to delete CSS }else{ bar.className='slide up'; //This is to add CSS //3vh is the height of that white triangle document.styleSheets[0].addRule('.slight:before','transform:translateY(3vh) rotateX(180deg)'); } } 

You can add the transformation to the CSS class, and simply toggle it.

CSS

.slide.up:before {
  transform: translateY(3vh) rotateX(180deg);
}

JS

var bar = document.querySelector('.slide')

function toggle() {
  var cl = bar.classList

  cl.toggle('down', cl.contains('up'))
  cl.toggle('up', !cl.contains('down'))
}

JSFiddle demo: https://jsfiddle.net/htq8ouyn/2/

Resources

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