js实现标题切换
实现标题切换的方法
在JavaScript中实现标题切换可以通过多种方式完成,以下是几种常见的方法:
使用DOM操作切换文本内容
通过获取DOM元素并修改其textContent或innerHTML属性实现标题切换。
const titleElement = document.querySelector('h1');
const titles = ['标题1', '标题2', '标题3'];
let currentIndex = 0;
function switchTitle() {
currentIndex = (currentIndex + 1) % titles.length;
titleElement.textContent = titles[currentIndex];
}
// 每2秒切换一次
setInterval(switchTitle, 2000);
使用CSS类切换显示
通过添加或移除CSS类来控制不同标题的显示状态。
<style>
.title { display: none; }
.title.active { display: block; }
</style>
<h1 class="title active">标题1</h1>
<h1 class="title">标题2</h1>
<h1 class="title">标题3</h1>
<script>
const titles = document.querySelectorAll('.title');
let currentIndex = 0;
function switchTitle() {
titles[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % titles.length;
titles[currentIndex].classList.add('active');
}
setInterval(switchTitle, 2000);
</script>
使用动画效果切换
结合CSS过渡或动画效果实现更平滑的标题切换。
<style>
.title-container {
position: relative;
height: 50px;
overflow: hidden;
}
.title {
position: absolute;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.title.active {
opacity: 1;
}
</style>
<div class="title-container">
<h1 class="title active">标题1</h1>
<h1 class="title">标题2</h1>
<h1 class="title">标题3</h1>
</div>
<script>
const titles = document.querySelectorAll('.title');
let currentIndex = 0;
function switchTitle() {
titles[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % titles.length;
titles[currentIndex].classList.add('active');
}
setInterval(switchTitle, 2000);
</script>
使用第三方库
如果需要更复杂的效果,可以考虑使用如Animate.css或GSAP等动画库。
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
<h1 id="dynamicTitle" class="animate__animated">标题1</h1>
<script>
const titleElement = document.getElementById('dynamicTitle');
const titles = ['标题1', '标题2', '标题3'];
let currentIndex = 0;
function switchTitle() {
titleElement.classList.remove('animate__fadeIn');
void titleElement.offsetWidth; // 触发重绘
currentIndex = (currentIndex + 1) % titles.length;
titleElement.textContent = titles[currentIndex];
titleElement.classList.add('animate__fadeIn');
}
setInterval(switchTitle, 2000);
</script>
这些方法可以根据具体需求选择使用,简单的文本切换可以使用第一种方法,需要动画效果时可以选择第三种或第四种方法。







