gpt4 book ai didi

javascript - 如何使文本出现在html中的滚动条上

转载 作者:太空狗 更新时间:2023-10-29 13:24:34 28 4
gpt4 key购买 nike

您好,我希望当我滚动经过某个文本或滚动到该文本所在的位置时出现该文本。出现时的效果应该有点像网站置顶的第一个效果http://namanyayg.com/ .

我希望使用纯 CSS 和 JS(即没有 jQuery)以最少的代码实现效果。

我在想,也许我会为一个跨度使用类似 display:none 属性的东西,然后当你滚动经过它时,display 变成了 block 但我不知道如何使用 javascript 触发效果。任何帮助,将不胜感激。

最佳答案

首先将要在滚动条上显示的文本或内容包裹在一个 div 中,以便根据滚动条显示隐藏 div。为您的目标 div 编写两个类。

您的 CSS:

/*Use this class when you want your content to be hidden*/
.BeforeScroll
{
height: 100px; /*Whatever you want*/
width: 100%; /*Whatever you want*/
.
.
display: none;
}


/*Use this class when you want your content to be shown after some scroll*/
.AfterScroll
{
height: 100px; /*Whatever you want*/
width: 100%; /*Whatever you want*/
.
.
display: block;
}

您的 HTML:

<!--Set class BeforeScoll to your target div-->

<div id = "divToShowHide" class = "BeforeScroll">Content you want to show hide on scroll</div>

您的脚本:

<!--include these script in head section or wherever you want-->

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js" type="text/javascript"></script>

<script type = "text/javascript">
$(document).ready(function(){
//Take your div into one js variable
var div = $("#divToShowHide");
//Take the current position (vertical position from top) of your div in the variable
var pos = div.position();
//Now when scroll event trigger do following
$(window).scroll(function () {
var windowpos = $(window).scrollTop();
//Now if you scroll more than 100 pixels vertically change the class to AfterScroll
// I am taking 100px scroll, you can take whatever you need
if (windowpos >= (pos.top - 100)) {
div.addClass("AfterScroll");
}
//If scroll is less than 100px, remove the class AfterScroll so that your content will be hidden again
else {
s.removeClass("AfterScroll");
}
//Note: If you want the content should be shown always once you scroll and do not want to hide it again when go to top agian, no need to write the else part
});
});
</script>

希望能解决您的问题。

关于javascript - 如何使文本出现在html中的滚动条上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307555/

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