在滑块中需要实现切换幻灯片时“键入”的效果。我使用Slick Slider作为滑块。工作示例http://test2.hotweb.com.ua/webbit/。
HTML:
<div class="header-slider-wrap">
<div class="header-slider">
<div class="slider-nav__left nav-btn-slider">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 477.175 477.175"><path d="M145.188 238.575l215.5-215.5c5.3-5.3 5.3-13.8 0-19.1s-13.8-5.3-19.1 0l-225.1 225.1c-5.3 5.3-5.3 13.8 0 19.1l225.1 225c2.6 2.6 6.1 4 9.5 4s6.9-1.3 9.5-4c5.3-5.3 5.3-13.8 0-19.1l-215.4-215.5z"/></svg>
</div>
<div class="slider-nav__right nav-btn-slider">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 477.175 477.175"><path d="M360.73 229.075l-225.1-225.1c-5.3-5.3-13.8-5.3-19.1 0s-5.3 13.8 0 19.1l215.5 215.5-215.5 215.5c-5.3 5.3-5.3 13.8 0 19.1 2.6 2.6 6.1 4 9.5 4 3.4 0 6.9-1.3 9.5-4l225.1-225.1c5.3-5.2 5.3-13.8.1-19z"/></svg>
</div>
<ul class="slider-item-list">
<li class="slider-item" style="background-color: #6495ED">
<div class="slider-text-wrap">
<div class="slider-text" data-text='Example text 1'></div>
</div>
</li>
<li class="slider-item" style="background-color: #BA55D3">
<div class="slider-text-wrap">
<div class="slider-text" data-text='Example text 2'></div>
</div>
</li>
<li class="slider-item" style="background-color: #8DEEEE">
<div class="slider-text-wrap">
<div class="slider-text" data-text='Example text 3'></div>
</div>
</li>
</ul>
</div>
</div>
JavaScript的:
printTextSlider();
function printTextSlider() {
var $btn = $('.nav-btn-slider'),
$ul = $('.slider-item-list'),
$activeLi = $ul.find('.slick-active'),
$text = $activeLi.find('.slider-text');
$text.addClass('is-active');
printText($text);
$btn.on('click', function() {
var $activeLi = $ul.find('.slick-active'),
$siblings = $activeLi.siblings().find('.slider-text'),
$text = $activeLi.find('.slider-text'),
id = $text.attr('id');
setTimeout(function() {
$siblings.removeClass('is-active');
}, 1000);
$text.addClass('is-active');
printText($('#'+id));
});
}
function printText(el) {
var a = el.data('text');
a = a.split('');
console.log(a);
el.text('');
var c = a.length;
j = 0;
setInterval(function() {
if(j < c) {
el.text(el.text() + a[j]);
j++;
}
else {
el.removeClass('after-line');
}
}, 100);
}
样式(SASS):
.slider-text-wrap {
max-width: 700px;
width: 100%;
margin: 0 auto;
padding-top: 230px;
}
.slider-text {
font-size: 36px;
word-wrap: break-word;
opacity: 0;
}
问题:切换幻灯片时,显示的文字不正确。 哪里我错了?
更新:我找到了一些有趣的插件 typed.js 并为此重写了js代码:
printTextSlider();
function printTextSlider() {
var $btn = $('.nav-btn-slider'),
$ul = $('.slider-item-list'),
$active = $ul.find('.slick-active'),
$span = $active.find('.slider-text'),
text = $span.data('text');
$span.typed({
strings: [text],
typeSpeed: 100,
startDelay: 1300,
showCursor: false,
});
$btn.on('click', function() {
var $active = $ul.find('.slick-active'),
$span = $active.find('.slider-text'),
text = $span.data('text');
printText($span, text);
});
}
function printText(el, text) {
el.typed({
strings: [text],
typeSpeed: 100,
startDelay: 1800,
showCursor: false
});
}
这是工作!