如果语句不适用于简单的JavaScript切换

时间:2017-09-06 23:02:12

标签: javascript html css css3 events

defaultEntryPoints = ["http", "https"] [web] address = ":8080" [entryPoints] [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" [entryPoints.https] address = ":443" compress = true [entryPoints.https.tls] [acme] email = "email@domain.com" storage = "acme.json" entryPoint = "https" onDemand = false OnHostRule = true [docker] endpoint = "unix:///var/run/docker.sock" domain = "traefik.example.com" watch = true exposedbydefault = false函数中,我们检查resize()元素是否具有类body。如果它包含switch,那么我们会在switch被触发时将其删除。如果它没有resize类,那么我们在触发函数时添加它。

但是,在单击按钮的下面的代码段中,它不能用作切换。它只被点击一次,它的原始状态无法恢复。

为什么这个简单的JavaScript不起作用,有什么方法可以解决这个问题?

switch
function resize() {
  var body = document.querySelector( 'body' );
  
  if( body.classList.contains( 'switch' ) ){
    body.classList.remove( 'shrink' ); 
  }
  else {
    body.classList.add( 'shrink' ); 
  }
}

var switcher = document.getElementById( 'switch' );
switcher.addEventListener( 'click', resize );
p {
  text-align: center;
  margin-bottom: 1rem;
  transition-property: color;
  transition-duration: 1.5s;
}
.bar {
  width: 22.5rem;
  height: 10rem;
  background-color: #555;
  border-radius: 5rem;
  position: relative;
  transition-property: background-color;
  transition-duration: 1.5s;
}
.knob {
  width: 12rem;
  height: 12rem;
  background-color: #000;
  border-radius: 10rem;
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY( -50% );
  transition-property: right, background-color;
  transition-duration: 1s, 1.5s;
}
:checked ~ label p { color: #888 }
:checked ~ label .bar { background-color: #888 }
:checked ~ label .knob {
  background-color: #777;
  right: 10.5rem
}
.shrink { transform: scale( 0.8 ) }

2 个答案:

答案 0 :(得分:1)

您正在检查是否存在shrink类,但尝试切换contains('switch')类。 library(ggplot2) library(tidyr) x <- 1:48 y <- rnorm(length(x)) z <- rnorm(length(x)) df <- data.frame(x,y,z) df <- gather(df, 'y', 'z', key = "group", value = "value") ggplot(df, aes(x = x, y = value, color = group)) + geom_line() + scale_color_manual(values=c("red", "green")) 永远不会是假的,因为你没有删除那个类。

答案 1 :(得分:1)

  

在resize()函数中,我们检查body元素是否具有类开关。如果它包含switch,那么我们在激活resize时将其删除。

但你不是。您正在添加和删除&#39;缩小&#39;类