《js 实现css在播放并实现样式》

230 阅读2分钟

1、项目名称

飞行的哆啦A梦

2、技术栈

html5 , css3 , javascript

3、功能模块

  • 开始播放
  • 暂停播放
  • 缓慢播放
  • 正常播放
  • 快速播放

4、项目展示

源码地址 在线预览

pc端 pc哆啦A梦.png 移动端 移动端哆啦A梦.jpg

html就不展示了,主要讲讲CSS动画和javascript的展示

5、代码实现

  • 项目CSS代码主要用到es6的模块化
  • 将CSS样式写入js文件当,export导出css,main.js接收
  • div标签实现代码自动打印,style标签实现样式
  • 竹蜻蜓旋转、眨眼睛、人物左右动
let string = `
/*接下来,我要画一个哆啦A梦*/

/*开始画竹蜻蜓了*/
.turn{
    width: 100px;
    height: 5px;
    background-color: gray;
    border-radius: 5px;
    border: 2px solid gray;
    z-index: 100;
    opacity: 0.6;
    position: absolute;
    top: 10px;
    /*开始旋转了*/
    animation: rotar .1s infinite linear;
}

@keyframes rotar {
    from{transform:rotate3D(0,1,0,0deg);}
    to{transform:rotate3D(0,1,0,360deg);}
}

//....

.right_empty{
    background-color: white;
    width: 48px;
    height: 48px;
    position: relative;
    overflow: hidden;
    animation: pulse 2s infinite;
    z-index: 1;
}

@keyframes pulse {
    to {
        bottom: 100px;
    }
    from {
        bottom: 0;
    }
}

//...省略代码

@keyframes volar{
    0%   {left:0px;}
    25%  {left:-10px;}
    50%  {left:0px;}
    75%  {left:10px;}
    100% {left:0px;}
}
`;
export default string;

js代码实现

  • 引入css字符串
  • 获取对应元素
import string from './style.js';
const textApp = document.getElementById('textApp');
const htmlApp = document.getElementById('htmlApp');
const buttonPause = document.getElementById('buttonPause');
const buttonPlay = document.getElementById('buttonPlay');
const buttonSlow = document.getElementById('buttonSlow');
const buttonNormal = document.getElementById('buttonNormal');
const buttonFast = document.getElementById('buttonFast');


let n = 1;
textApp.innerText = string.substr(0, n);
htmlApp.innerHTML = string.substr(0, n);

let time = 100;

const run = () => {
  n += 1;
  if (n > string.length) {
    window.clearInterval(id);
    return;
  }
  textApp.innerText = string.substr(0, n);
  htmlApp.innerHTML = string.substr(0, n);
  textApp.scrollTop = textApp.scrollHeight;
}
const play = ()=>{
 return setInterval(run, time);
}
const pause = ()=>{
  window.clearInterval(id);
}

let id = play();
buttonPause.onclick = () => {
    pause();
  }
  buttonPlay.onclick = () => {
     id = play();
  }
  buttonSlow.onclick = () =>{
    pause();
    time = 300;
     id = play();
  }
  buttonNormal.onclick = () =>{
    pause();
    time = 100;
    id = play();
  }
  buttonFast.onclick = () =>{
    pause();
    time = 0;
    id = play();
  }
  
  • substr获取字符串,切割字符串,
  • textApp.innerTexthtmlApp.innerHTML加入页面对应的位置
  • n表示当前css字符串的索引,使用setInterval() 函数和clearInterval()每一秒执行函数和停止执行 运行会出现一个问题,就是css字符串打印,总还是停留在前面,不能索引当前,解决办法,设置scrollHeight滚动条,追踪打印索引,会自动跟上打印结果。
  • 按钮实现,绑定一个点击事件即可,暂停开始事件,使用setInterval() 函数和clearInterval()
  • 速度播放改变time的值,可以达到变速效果