gpt4 book ai didi

javascript - 滚动时减慢淡入淡出的文本

转载 作者:行者123 更新时间:2023-11-30 09:57:11 25 4
gpt4 key购买 nike

我想在游戏中创建一个效果 A Dark Room .在游戏中,文本执行我试图复制的 2 个功能:

  1. 新文本添加在旧文本之上和之下。随着游戏的进行,这会将较旧的文本推到页面下方。
  2. 当文本被向下推到页面时,它会慢慢淡出视野。

我完全坚持#1。我猜是类似 insertAfter 的东西对比InsertBefore ,但我不认为是这样。

现在,我当前的代码是:

$("<p>You picked up a sword.</p>").hide().insertBefore("#placeholder").fadeIn(1000);

然后将新文本插入到任何旧文本下方。

至于#2,我将其缩小到将文本放在一个 div 中并设置 overflow: hidden .我很确定有一些 JS 或 CSS 在页面上变低时会慢慢淡出。这就是我被困的地方。

我认为像这样的东西是关键:

$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var height = $(window).height();
$('.logo_container, .slogan').css({
'opacity': ((height - scrollTop) / height)
});
});

我在这里找到了一个 fiddle http://jsfiddle.net/0ma4na3t/1/这或多或少是用 div 来完成的。我会说,在那把 fiddle 上,我不明白在哪里 .slogan来自。我在 fiddle 代码中看不到它。我认为那不是 jquery 或 JS 命令,是吗?

最佳答案

如果你想用纯 Javascript 来做,那很容易。在这里,我允许最多显示 10 个句子,删除超出此范围的任何句子。如果您愿意,您可以轻松地将此相关顶部设置为您的窗口大小。

function prependAndFade(item, text){
// Find the item we want to prepend to
var p = document.getElementById(item);
// Create a fresh paragraph and enter the content
var e = document.createElement('p');
e.textContent = text;

// Insert the paragraph (either before anything else or as single child)
if(p.childNodes.length) p.insertBefore(e, p.childNodes[0])
else p.appendChild(e);

// Use a timeout to allow CSS to fade in the text
setTimeout(function(){
// Loop through any element, reducing the opacity as we reach 10
for(var o = 1, i = 0; i < p.childNodes.length; i++){
// Check if the childNode is a P tag
// Since empty spaces etc.. Are also children, but not elements
if(p.childNodes[i].tagName === 'P'){
o-=.1
p.childNodes[i].style.opacity = o;
}
// If the opacity is 0, remove the remaining elements (save resources)
if(o === 0) p.removeChild(p.childNodes[i]);
}
}, 100);
}
p {
opacity: 0;
-webkit-transition: opacity 500ms;
transition: opacity 500ms;
}
<input type="text" onchange="prependAndFade('fader', this.value); this.value = '';" />

<dfiv id="fader"></div>

关于javascript - 滚动时减慢淡入淡出的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480533/

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