我正在尝试在一个横幅文本上创建一个打字机效果,一旦这个元素出现在视区中。我差一点就把它弄好了,但我还是有一些问题我自己似乎解决不了:
我正在使用ACF获取内容。我还尝试将代码重写为jquery,但这似乎也行不通。
HTML/PHP
echo '<div class="contentBlock featured bg-black">';
echo '<div class="textWrapper">';
echo '<h2 id="original" style="display:none;">'. get_sub_field('grote_titel') .'</h2>';
echo '<h2 id="typewriter"></h2>';
echo '</div>';
echo '</div>';
jQuery/JS
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
$('.contentBlock.featured').each(function() {
if ( $(this).isInViewport()) {
var str = document.getElementById('original').innerText,
i = 0,
isTag,
text;
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('typewriter').innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 80);
}());
}
});
});
对于第一个问题,只需先进行以下测试:
(function type() {
if (text === str) return;
text = str.slice(0, ++i);
对于闪烁,您执行打字机,每次您滚动和标题是在视口。这很正常。为了避免闪烁,你有2种解决方案:
>
你可以把打字机的速度稍微提高一点,比如提高到40(不是最好的)
您可以避免在键入处于活动状态时重新启动键入->使用布尔值(此解决方案在代码片段中)
null
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
var typing = false;
$(window).on('resize scroll', function() {
$('.contentBlock.featured').each(function() {
if ( $(this).isInViewport() && !typing) {
typing = true;
var str = document.getElementById('original').innerText,
i = 0,
isTag,
text;
(function type() {
if (text === str) {typing= false;return;}
text = str.slice(0, ++i);
document.getElementById('typewriter').innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 80);
}());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contentBlock featured bg-black">
<div class="textWrapper">
<h2 id="original" style="display:none;">Big Title ttttttttx</h2>
<h2 id="typewriter"></h2>
</div>
<div class="just text to create scroll">
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br>the td's are not updated when you select td, its the reason you have older values, i dont see event about that, so i suggest you to wait the value of tds are changed by testing the month, you could add year if needed:
</div>
</div>