简体   繁体   English

如何根据视口中的部分将 class 添加到正文标记

[英]How to add a class to body tag based on the section which is in viewport

Hey I am new in jquery and i am stuck, I have html like this嘿,我是 jquery 的新手,我被卡住了,我有这样的 html

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

So now if touch section is in viewport then add class to body (body class name is " touch-active ")所以现在如果触摸部分在视口中,则将 class 添加到主体(主体 class 名称为“触摸活动”)

and i am trying this code but it is not working for me:我正在尝试这段代码,但它对我不起作用:

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

Thanks in advance:)提前致谢:)

To achieve this you can use an IntersectionObserver to detect when an element comes in to view.为此,您可以使用 IntersectionObserver 来检测元素何时进入查看。 From there you can remove all classes from the body and replace it with a new class based on the visible section .从那里您可以从body中删除所有类,并根据可见section将其替换为新的 class 。 Try this:尝试这个:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM