[英]Javascript Fade when in ViewPort
我正在学习 Javascript 并希望使用以下功能来使用香草 javascript 而不是 Jquery 产生淡化效果。 代码在我修改后不再运行。 有人可以帮我看看我做错了什么吗? 作为参考,我将它与 codepen.io/staffan-ad/pen/zaLevE 一起使用
原装 Jquery:
$(document).on("scroll", function() {
var pageTop = $(document).scrollTop();
var pageBottom = pageTop + $(window).height();
var tags = $(".tag");
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if ($(tag).position().top < pageBottom) {
$(tag).addClass("visible");
} else {
$(tag).removeClass("visible");
}
}
});
我的版本:
document.addEventListener("scroll", function() {
const pageTop = document.scrollTop;
const pageBottom = pageTop + window.height;
const tags = document.querySelector(".tag");
for (var i = 0; i <tags.length; i++) {
var tag = tags[i];
if (tag.position().top < pageBottom) {
tag.addClass("visible");
} else {
tag.removeClass("visible");
}
}
});
document.addEventListener("scroll", function () {
var tags = document.querySelectorAll(".tag");
var windowHeight = window.innerHeight;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
var tagPosition = tag.getBoundingClientRect();
if (tagPosition.top < windowHeight) {
tag.classList.add("visible");
} else {
tag.classList.remove("visible");
}
}
});
document.querySelector
返回单个文档 object。 定位多个元素时应使用document.querySelectorAll
,并且.addClass
中不存在 .addClass。
http://youmightnotneedjquery.com/ - 用于 Jquery 到 Vanilla JS 的转换
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.