嘿,我是jquery的新手,我被卡住了,我有这样的html
<section id="help">Help</section>
<section id="touch">Touch</section>
<section id="payment">Payment</section>
<section id="toys">Toys</section>
因此,现在如果触摸部分在视口中,则将类添加到主体(主体类名称为“ touch-active ”)
我正在尝试此代码,但对我不起作用:
jQuery(document).ready(function(){
if (jQuery('section').is(':visible')){
jQuery('body').addClass(.attr('id + active'));;
}
});
提前致谢 :)
为此,您可以使用IntersectionObserver来检测何时有元素进入视图。在此处,您可以从中删除所有类,body
并根据visible替换为新类section
。试试这个:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句