如何使用伪元素从类中添加和删除CSS代码?

时间:2017-07-10 00:13:10

标签: javascript css 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>
&#13;
&#13;
&#13;

红色矩形顶部的白色三角形是用伪元素:before。我想要做的是当滑动标签向上时,白色三角形应指向下方。要做到这一点,我想写一个JS代码,它将使用伪元素向该类添加变换CSS,该元素将三角形向下平移高度并旋转180度。

我在this developer blog上找到要添加的JS代码,但它不起作用,我不知道如何在标记关闭时删除该代码。

&#13;
&#13;
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)');
   }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您可以将转换添加到CSS类,只需切换它。

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演示:https://jsfiddle.net/htq8ouyn/2/

资源