【问题标题】:toggleClass removes all other existing classestoggleClass 删除所有其他现有类
【发布时间】:2021-02-14 06:25:05
【问题描述】:

我的目标是向body 添加/替换新类,由下面的“id”变量动态提供。该变量的值是滚动时传入视口的每个section 的实际id。因此,当不同的sections(显然具有不同的ids)通过视口时,它们将它们的id 名称作为新的body 传递给class,添加一个新的或替换以前的class。将toggleClass 与布尔值true 一起使用,它可以工作,但它替换了body 标签上的所有其他类,由Wordpress 模板固有地给出,这当然会破坏一切别的。有道理?任何见解都会有所帮助。

var id = entry.target.getAttribute('id');

var newClass = $('body').toggleClass(id, true);

【问题讨论】:

  • 为什么不干脆做$('body').removeClass(id);
  • 谢谢。目标是让类被 id 变量(id 名称)的值动态替换,这样我就可以对主体应用不同的样式。上下文是我正在使用 Intersection Observer 来确定页面的各个部分(具有不同的 id)何时进入视口,将 id 名称作为类传递给 body 标签,然后用另一个替换新的 body 类当另一部分进入视口时。
  • id 给了你正确的价值吗?什么在这里不起作用?
  • 一切正常,除了 toggleClass 正在删除 Wordpress 附加到 body 标记的所有其他类,并将它们全部替换为我想要的类(由 id 变量提供)。
  • 你试过这样$('body').removeClass(id);吗?

标签: jquery intersection-observer


【解决方案1】:

你只需要传递你想要切换的类名

$('div').toggleClass('c3');
.c1 {
  font-size: 5rem;
}

.c3 {
  color: red;
}

.c2 {
  padding: 2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="c1 c2 c3">TEST</div>

【讨论】:

  • 谢谢,但是类名是由变量“id”动态生成的。我应该更明确一点。
  • @pjldesign 您应该为此添加一个示例
【解决方案2】:

如果你想选择(我不知道你的规则)你身体的哪个部分必须添加所需的类:你可以像这样枚举你身体的所有标签:

console.log("there are " + $('body *').length + " tags in the body");
  

$('body *').each(function(){
  // here its an example of data you could access
  // you could test following your condition and modify or not the class corresponding
  console.log("tag: " + $(this).prop("tagName"));//display the tag
  console.log("class: " + $(this).attr("class")); //display the class or undefined
  console.log("content: " + $(this).html());      //display the content of tag
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多