更改div的body类并在div更改时恢复默认值

时间:2016-04-21 12:19:25

标签: html html5

我想更改特定body的{​​{1}}的类,并在div更改时恢复默认值。

例如:div身体的#class为新

<div id='test'></div>

提前致谢!

1 个答案:

答案 0 :(得分:0)

  

这可能不是有效的方法。但既然你问了一个例子我   我提供一个。

此类工作可用的工具很少,例如 Mutation Observer 及其浏览器Compatibality

但如果你想要一个肮脏的工作,那么下面是我的样本。

您可以使用Jquery检查每x秒的div id并相应地设置body类。这是一个示例代码。

//demo purpose, this script toggles the div id to be test and test2 for each click.
$('button').on('click', function() {
  var currID = $('.demo').attr('id');
  if (currID === "test") {
    $('.demo').attr('id', "test2");
  } else {
    $('.demo').attr('id', "test");
  }
});


//below is the actual logic, this will change the body class according to div id
setInterval(function() {
  var currID = $('.demo').attr('id');
  if (currID === "test") {
    $('body').removeClass('default').addClass('new');
  } else {
    $('body').removeClass('new').addClass('default');
  }
}, 100); // run this interval every 100 miliseconds, you can set it to your preference
.new {
  background-color: green;
}
.default {
  background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="new" style="height:200px;">
  <div id="test" class="demo"></div>
  <button>Toggle Div's Id</button>
</body>

相关问题