从body(parent)继承css值不起作用

时间:2017-01-27 21:28:00

标签: javascript css css3

我想要使用JavaScript禁用所有css转换。我将transition: none添加到正文(通过JavaScript),但正文中的元素仍然有转换。

当然我可以循环遍历所有元素,并添加transition = 'none';,但我确信有一种更好的方法可以临时禁用所有元素的css转换。这是一个示例代码:

JSFiddle

var sample = document.getElementById('sample');

sample.addEventListener('click', function() {
  if (document.body.style.transition === 'none') {
    document.body.style.transition = '';
  } else {
    document.body.style.transition = 'none';
  }
})
#sample {
  width: 200px;
  height: 100px;
  background: lawngreen;
  transition: transform 500ms ease;
}
#sample:hover {
  transform: translateX(50px);
}
<div id="sample">Hover over me to move
  <br />Click to disable transition</div>

3 个答案:

答案 0 :(得分:1)

body或父标记添加新的类名。使用新的父选择器.animated #sample设置转场:

<body class="animated">
    <div id="sample"></div>
</body>

......和风格:

#sample {
    width: 200px;
    height: 100px;
    background: lawngreen;
}

.animated #sample {
    transition: transform 500ms ease;
}

.animated #sample:hover {
    transform: translateX(50px);
}

要禁用所有子项的动画,只需从正文或父标记中删除.animated类。 修改过的小提琴:https://jsfiddle.net/xjxauu0h/1/

答案 1 :(得分:0)

你想要在身体上使用一个课程,这样你就可以打开和关闭它。

&#13;
&#13;
var sample = document.getElementById('sample');
document.body.classList.add('transitioner');

sample.addEventListener('click', function() {
  if (document.body.classList && document.body.classList.length) {
    document.body.classList.remove('transitioner');
  } else {
    document.body.classList.add('transitioner');
  }
  console.log(document.body.classList);
})
&#13;
#sample {
  width: 200px;
  height: 100px;
  background: lawngreen;
}
.transitioner *{
  transition: transform 500ms ease;
}
#sample:hover {
  transform: translateX(50px);
}
&#13;
<div id="sample">Hover over me to move
  <br />Click to disable transition</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

var sample = $('#sample');
var body = $('body');

sample.click(function() {
  body.toggleClass('notransition notransform');
});
#sample {
  width: 200px;
  height: 100px;
  background: lawngreen;
  transition: transform 500ms ease;
}
#sample:hover {
  transform: translateX(50px);
}

.notransition.notransform #sample {
  background: HotPink; 
}

.notransition * { 
  -webkit-transition: none !important; 
  -moz-transition: none !important; 
  -o-transition: none !important; 
  -ms-transition: none !important; 
  transition: none !important; 
} 

.notransform * { 
  -webkit-transform: none !important; 
  -moz-transform: none !important; 
  -o-transform: none !important; 
  -ms-transform: none !important; 
  transform: none !important; 
} 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample">Hover over me to move
  <br />Click to disable transition</div>

相关问题