帮我写一个js的走马灯添加动态文字怎么实现
这里提供一种基于jQuery的实现方式:
HTML结构:
<div class="carousel">
<ul class="carousel-list">
<li>图片1</li>
<li>图片2</li>
<li>图片3</li>
</ul>
<div class="carousel-text"></div>
</div>
CSS样式:
.carousel {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
.carousel-list {
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 0;
left: 0;
}
.carousel-list li {
float: left;
width: 600px;
height: 400px;
}
.carousel-text {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 50px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 24px;
line-height: 50px;
text-indent: 20px;
white-space: nowrap;
overflow: hidden;
}
JavaScript代码:
$(function() {
var $carousel = $('.carousel');
var $list = $carousel.find('.carousel-list');
var $items = $list.find('li');
var $text = $carousel.find('.carousel-text');
var len = $items.length;
var index = 0;
var interval = 3000;
var timer;
// 初始化
$list.css('width', len * 100 + '%');
$items.css('width', 100 / len + '%');
$text.text($items.eq(index).data('text'));
// 自动切换
function autoSwitch() {
timer = setInterval(function() {
index++;
if (index >= len) {
index = 0;
}
switchTo(index);
}, interval);
}
// 切换到指定项
function switchTo(idx) {
$list.stop().animate({left: -idx * 100 + '%'}, 500);
$text.stop().fadeOut(200, function() {
$(this).text($items.eq(idx).data('text')).fadeIn(200);
});
}
// 鼠标悬停暂停自动切换
$carousel.hover(function() {
clearInterval(timer);
}, function() {
autoSwitch();
});
// 启动自动切换
autoSwitch();
});
注意事项:
- 需要引入jQuery库。
- 在每个图片项上设置
data-text属性来指定对应的动态文字内容。
原文地址: https://www.cveoy.top/t/topic/McC 著作权归作者所有。请勿转载和采集!