我想将以下代码转换为纯JavaScript。
$(function () {
$('h2,.single').on('inview', function () {
$(this).addClass('is-show');
});
});我试了很多时间,但还是想不出怎么做。有什么帮助吗?
发布于 2020-02-17 19:26:49
Inview是一个旧的插件,用来解决现在有web API的问题,只要你不需要支持IE,你可以使用intersection observer来做这件事。
如果没有任何例子或进一步解释你需要的东西如何工作,就很难猜测你想要实现什么。但这里有一个基本的实现,它将模仿您提供的极小的JQuery。
const sections = [].slice.call(document.querySelectorAll(".single"));
function createObserver(el) {
let observer;
const options = {
root: null,
rootMargin: "0px",
threshold: 0.5
};
observer = new IntersectionObserver(handleIntersect, options);
observer.observe(el);
}
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
let box = entry.target;
let visible = entry.intersectionRatio;
if(visible > 0.5) {
box.classList.add('is-show');
} else {
box.classList.remove('is-show');
}
});
}
const setup = (sections) => {
for (let i in sections) {
const el = sections[i];
createObserver(el);
}
}
setup(sections);.single {
padding: 2rem;
background: tomato;
color: #fff;
margin: 600px 0;
transition: all .5s ease-out;
opacity: 0;
}
.is-show {
opacity: 1
}<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
<h2 class="single">I'm an H2 Element in frame</h2>
发布于 2020-02-17 18:07:59
除了事件之外,您可以使用以下命令:
(function() {
document.querySelector("h2, .single").addEventListener("click", function(){
this.classList.add("is-show");
});
})();我没有找到inview的等价物。你可以参考this。
https://stackoverflow.com/questions/60259146
复制相似问题