GSAP这个动画库非常强大,用户与页面的互动性更强,访问过程也就变得更有趣。
无奈有些动效是收费的,比如splittext,要想实现一些简单的文字效果,就只能靠我们自己动动脑子了。
要实现的效果大概如下:
代码奉上:
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "pingfang";
}
.move_box{
overflow: hidden;
}
.info_main{
margin-top: 200px;
margin-bottom: 200px;
width: 100%;
height: 100vh;
position: relative;
}
.text_box{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
letter-spacing: 2px;
word-spacing: 2px;
line-height: 2;
}
.text_box h2{
font-size: 20px;
color: #222;
}
.text_box h4{
font-size: 16px;
color: #444;
margin-top: 10px;
margin-bottom: 6px;
}
.text_box h5{
font-size: 14px;
color: #555;
margin-bottom: 10px;
font-weight: normal;
}
.text_box p{
font-size: 16px;
color: #666;
}
</style>
</head>
<body>
<div class="move_box">
<div class="info_main">
<div class="text_box">
<h2>水调歌头·明月几时有</h2>
<h4>苏轼</h4>
<h5>丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。</h5>
<p>明月几时有?把酒问青天。</p>
<p>不知天上宫阙,今夕是何年。</p>
<p>我欲乘风归去,又恐琼楼玉宇,高处不胜寒。</p>
<p>起舞弄清影,何似在人间。</p>
<p>转朱阁,低绮户,照无眠。</p>
<p>不应有恨,何事长向别时圆?</p>
<p>人有悲欢离合,月有阴晴圆缺,此事古难全。</p>
<p>但愿人长久,千里共婵娟。</p>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
<script>
$(function(){
textAddHtml();
textAppear();
})
function textAppear(){
let textmove = gsap.timeline({
scrollTrigger: {
trigger: '.info_main',
start: 'top top',
end: '+=300%',
scrub: 1,
pin: true
},
});
gsap.utils.toArray(".info_main .text_box span").forEach(function(elem) {
textmove.to(elem, { color:"#ff1010", duration: 0.007})
})
}
// 将文字加上span标签
function textAddHtml(){
let texthtml = '';
// h2加span
let titleArr = $(".text_box h2").text().split('');
texthtml += '<h2>'
titleArr.forEach(item => {
texthtml += '<span>'+item+'</span>'
})
texthtml += '</h2>'
// h4加span
let authorArr = $(".text_box h4").text().split('');
texthtml += '<h4>'
authorArr.forEach(item => {
texthtml += '<span>'+item+'</span>'
})
texthtml += '</h4>'
// h5加span
let xuArr = $(".text_box h5").text().split('');
texthtml += '<h5>'
xuArr.forEach(item => {
texthtml += '<span>'+item+'</span>'
})
texthtml += '</h5>'
// p加span
$(".text_box p").each(inx => {
let poemArr = $(".text_box p").eq(inx).text().split('');
texthtml += '<p>'
poemArr.forEach(citem => {
texthtml += '<span>'+citem+'</span>'
})
texthtml += '</p>'
})
// 重新赋值
$(".info_main .text_box").html(texthtml);
}
</script>
</body>
</html>