gpt4 book ai didi

javascript - 当我通过滚动到达它时,元素没有出现?

转载 作者:行者123 更新时间:2023-11-28 02:52:37 27 4
gpt4 key购买 nike

我试图让元素在我通过滚动到达它时淡入。但是我的 JavaScript 不工作,我不知道哪里出了问题。目前我正在努力学习 JavaScript,所以请不要用 JQuery 回答!

这是我的代码片段:

//variables

var textElement = document.querySelectorAll(".service");
var yScroll = window.scrollTop;
var yPos = textElement.offsetTop / 2;

// function

function scrollFun() {
if (yScroll > yPos) {
textElement.style.opacity = '1';
console.log(yPos);
} else {
textElement.style.opacity = '0';
}
}

window.addEventListener("scroll", scrollFun);
.service {
width: 600px;
height: 600px;
background-color: black;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>

<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>

<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>

<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>

<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
</p>

<div class="service">
<!-- the element that i want to be reveald -->
</div>

最佳答案

首先,您需要将选择器设置为选择 mike d 评论中提到的第一个元素。

其次,var yScroll = window.scrollTop; 需要是 var yScroll = window.scrollY;

第三,窗口滚动位置的评估需要在函数体内:

function scrollFun() {
var yScroll = window.scrollY;
if (yScroll > yPos) {
textElement.style.opacity = '1';
console.log(yPos);
} else {
textElement.style.opacity = '0';
}
}

关于javascript - 当我通过滚动到达它时,元素没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38771528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com