提问者:小点点

我有多个section,当section在viewport中时,将class添加到body中,并将class name添加到body中,如


嘿,我是jquery的新手,我被困住了,我有这样的html

<section id="help">Help</section>
<section id="touch">Touch</section>
<section id="payment">Payment</section>
<section id="toys">Toys</section>

所以现在,如果touch部分在viewport中,则向body添加类(body类名为“touch-active”)

我正在尝试这段代码,但它对我不起作用:

jQuery(document).ready(function(){
   if (jQuery('section').is(':visible')){
         jQuery('body').addClass(.attr('id + active'));;
    }
 });

提前致谢:)


共1个答案

匿名用户

为了实现这一点,您可以使用IntersectionObserver来检测元素何时进入视图。从那里,您可以删除正文中的所有类,并用一个基于可见的的新类替换它。试试看:

null

var targets = document.querySelectorAll('section')
var obsOptions = {
  root: null, // measure against the viewport
  threshold: .5 // how much of the element should be visible before handler is triggered
}

let handler = (entries, opts) => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > opts.thresholds[0]) {
      document.body.classList.remove(...document.body.classList);
      document.body.classList.add(entry.target.id + '-active');
    }
  })
}

targets.forEach(el => {
  var observer = new IntersectionObserver(handler, obsOptions);
  observer.observe(el);
})
section {
  height: 250px;
}

body.help-active { background-color: #FFFFFF; }
body.touch-active { background-color: #DDDDDD; }
body.payment-active { background-color: #BBBBBB; }
body.toys-active { background-color: #999999; }
<section id="help">Help</section>
<section id="touch">Touch</section>
<section id="payment">Payment</section>
<section id="toys">Toys</section>