当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue.js实现会动的简历(包含底部导航功能,编辑功能)

vue.js实现会动的简历(包含底部导航功能,编辑功能)

2019年07月23日  | 移动技术网IT编程  | 我要评论

久草免费线资源站,xman26期,雪豹之特战出击

在网上看到一个这样的网站,strml 它的效果看着十分有趣,如下图所示:


这个网站是用 react.js 来写的,于是,我就想着用 vue.js 也来写一版,开始撸代码。

首先要分析打字的原理实现,假设我们定义一个字符串 str ,它等于一长串注释加 css 代码,并且我们看到,当 css 代码写完一个分号的时候,它写的样式就会生效。我们知道要想让一段 css 代码在页面生效,只需要将其放在一对 <style> 标签对中即可。比如:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>js bin</title>
</head>
<body>
 红色字体
 <style>
 body{
  color:#f00;
 }
 </style>
</body>
</html>

你可以狠狠点击此处 查看效果。

当看到打字效果的时候,我们不难想到,这是要使用 间歇调用(定时函数:setinterval()) 或 超时调用(延迟函数:settimeout()) 加 递归 去模拟实现 间歇调用 。一个包含一长串代码的字符串,它是一个个截取出来,然后分别写入页面中,在这里,我们需要用到字符串的截取方法,如 slice(),substr(),substring() 等,选择用哪个截取看个人,不过需要注意它们之间的区别。好了,让我们来实现一个简单的这样打字的效果,如下:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>js bin</title>
</head>
<body>
 <div id="result"></div>
 <script>
  var r = document.getelementbyid('result');
  var c = 0;
  var code = 'body{background-color:#f00;color:#fff};'
  var timer = setinterval(function(){
   c++;
   r.innerhtml = code.substr(0,c);
   if(c >= code.length){
   cleartimeout(timer);
   }
  },50)
 </script>
</body>
</html>

你可以狠狠点击此处查看效果。好的,让我们来分析一下以上代码的原理,首先放一个用于包含代码显示的标签,然后定义一个包含代码的字符串,接着定义一个初始值为 0 的变量,为什么要定义这样一个变量呢?我们从实际效果中看到,它是一个字一个字的写入到页面中的。初始值是没有一个字符的,所以,我们就从第 0 个开始写入, c 一个字一个字的加,然后不停的截取字符串,最后渲染到标签的内容当中去,当 c 的值大于等于了字符串的长度之后,我们需要清除定时器。定时函数看着有些不太好,让我们用超时调用结合递归来实现。

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>js bin</title>
</head>
<body>
 <div id="result"></div>
 <script>
  var r = document.getelementbyid('result');
  var c = 0;
  var code = 'body{background-color:#f00;color:#fff};';
  var timer;
  function write(){
  c++;
  r.innerhtml = code.substr(0,c);
  if(c >= code.length && timer){
   cleartimeout(timer)
  }else{
   settimeout(write,50);
  }
 }
 write();
 </script>
</body>
</html>

你可以狠狠点击此处 查看效果。

好了,到此为止,算是实现了第一步,让我们继续,接下来,我们要让代码保持空白和缩进,这可以使用 <pre> 标签来实现,但其实我们还可以使用css代码的 white-space 属性来让一个普通的 div 标签保持这样的效果,为什么要这样做呢,因为我们还要实现一个功能,就是编辑它里面的代码,可以让它生效。更改一下代码,如下:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>js bin</title>
 <style>
 #result{
  white-space:pre-wrap;
  oveflow:auto;
 }
 </style>
</head>
<body>
 <div id="result"></div>
 <script>
  var r = document.getelementbyid('result');
  var c = 0;
  var code = `
  body{
   background-color:#f00;
   color:#fff;
  }
  `
  var timer;
  function write(){
  c++;
  r.innerhtml = code.substr(0,c);
  if(c >= code.length && timer){
   cleartimeout(timer)
  }else{
   settimeout(write,50);
  }
 }
 write();
 </script>
</body>
</html>

你可以狠狠点击此处 查看效果。

接下来,我们还要让样式生效,这很简单,将代码在 style 标签中写一次即可,请看:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>js bin</title>
 <style>
 #result{
  white-space:pre-wrap;
  overflow:auto;
 }
 </style>
</head>
<body>
 <div id="result"></div>
 <style id="mystyle"></style>
 <script>
  var r = document.getelementbyid('result'),
   t = document.getelementbyid('mystyle');
  var c = 0;
  var code = `
   body{
   background-color:#f00;
   color:#fff;
   }
  `;
  var timer;
  function write(){
  c++;
  r.innerhtml = code.substr(0,c);
  t.innerhtml = code.substr(0,c);
  if(c >= code.length){
   cleartimeout(timer);
  }else{
   settimeout(write,50);
  }
  }
  write();
 </script>
 
</body>
</html>

你可以狠狠点击此处 查看效果。

我们看到代码还会有高亮效果,这可以用正则表达式来实现,比如以下一个 demo :

<!doctype html>
<html lang="en">

<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <meta http-equiv="x-ua-compatible" content="ie=edge" />
 <title>代码编辑器</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }

  .ew-code {
   tab-size: 4;
   -moz-tab-size: 4;
   -o-tab-size: 4;
   margin-left: .6em;
   background-color: #345;
   white-space: pre-wrap;
   color: #f2f2f2;
   text-indent: 0;
   margin-right: 1em;
   display: block;
   overflow: auto;
   font-size: 20px;
   border-radius: 5px;
   font-style: normal;
   font-weight: 400;
   line-height: 1.4;
   font-family: consolas, monaco, "宋体";
   margin-top: 1em;
  }

  .ew-code span {
   font-weight: bold;
  }
 </style>
</head>

<body>
 <code class="ew-code">
  <div id="app">
   <p>{{ greeting }} world!</p>
  </div>
 </code>
 <code class="ew-code">
  //定义一个javascript对象
  var obj = { 
   greeting: "hello," 
  }; 
  //创建一个实例
  var vm = new vue({ 
   data: obj 
  });
  /*将实例挂载到根元素上*/
  vm.$mount(document.getelementbyid('app'));
 </code>
 <script>
  var lightcolorcode = {
   importantobj: ['json', 'window', 'document', 'function', 'navigator', 'console', 'screen', 'location'],
   keywords: ['if', 'else if', 'var', 'this', 'alert', 'return', 'typeof', 'default', 'with', 'class', 'export', 'import', 'new'],
   method: ['vue', 'react', 'html', 'css', 'js', 'webpack', 'babel', 'angular', 'bootstap', 'jquery', 'gulp','dom'],
   // special: ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\\", "(", ")", "/", "%", ":", "=", ';']
  }
  function sethighlight(el) {
   var htmlstr = el.innerhtml;
   //匹配单行和多行注释
   var regxspace = /(\/\/\s?[^\s]+\s?)|(\/\*(.|\s)*?\*\/)/gm,
    matchstrspace = htmlstr.match(regxspace),
    spacelen;
   //匹配特殊字符
   var regxspecial = /[`~!@#$%^&.{}()_\-+?|]/gim,
    matchstrspecial = htmlstr.match(regxspecial),
    speciallen;
   var flag = false;
   if(!!matchstrspecial){
     speciallen = matchstrspecial.length;
    }else{
     speciallen = 0;
     return;
    }
    for(var k = 0;k < speciallen;k++){
     htmlstr = htmlstr.replace(matchstrspecial[k],'<span style="color:#b9ff01;">' + matchstrspecial[k] + '</span>');
    }
   for (var key in lightcolorcode) {
    if (key === 'keywords') {
     lightcolorcode[key].foreach(function (imp) {
      htmlstr = htmlstr.replace(new regexp(imp, 'gim'), '<span style="color:#00ff78;">' + imp + '</span>')
     })
     flag = true;
    } else if (key === 'importantobj') {
     lightcolorcode[key].foreach(function (kw) {
      htmlstr = htmlstr.replace(new regexp(kw, 'gim'), '<span style="color:#ec1277;">' + kw + '</span>')
     })
     flag = true;
    } else if (key === 'method') {
     lightcolorcode[key].foreach(function (mt) {
      htmlstr = htmlstr.replace(new regexp(mt, 'gim'), '<span style="color:#52eeff;">' + mt + '</span>')
     })
     flag = true;
    }
   }
   if (flag) {
    if (!!matchstrspace) {
     spacelen = matchstrspace.length;
    } else {
     spacelen = 0;
     return;
    }
    for(var i = 0;i < spacelen;i++){
     var curfont;
     if(window.innerwidth <= 1200){
      curfont = '12px';
     }else{
      curfont = '14px';
     }
     htmlstr = htmlstr.replace(matchstrspace[i],'<span style="color:#899;font-size:'+curfont+';">' + matchstrspace[i] + '</span>');
    }
    el.innerhtml = htmlstr;
   }
  }
  var codes = document.queryselectorall('.ew-code');
  for (var i = 0, len = codes.length; i < len; i++) {
   sethighlight(codes[i])
  }

 </script>
</body>
</html>

你可以狠狠点击此处 查看效果。

不过这里为了方便,我还是使用插件 prism.js ,另外在这里,我们还要用到将一个普通文本打造成 html 网页的插件 marked.js 。

接下来分析如何暂停动画和继续动画,很简单,就是清除定时器,然后重新调用即可。如何让编辑的代码生效呢,这就需要用到自定义事件 .sync 事件修饰符,自行查看官网 vue.js 。

虽然这里用原生 js 也可以实现,但我们用 vue-cli 结合组件的方式来实现,这样更简单一些。好了,让我们开始吧:

新建一个 vue-cli 工程(步骤自行百度):

新建一个 styleeditor.vue 组件,代码如下:

<template>
 <div class="container">
  <div class="code" v-html="codeinstyletag"></div>
  <div class="styleeditor" ref="container" contenteditable="true" @input="updatecode($event)" v-html="highlightedcode"></div>
 </div>
</template>
<script>
 import prism from 'prismjs'
 export default {
  name:'editor',
  props:['code'],
  computed:{
   highlightedcode:function(){
    //代码高亮
    return prism.highlight(this.code,prism.languages.css);
   },
   // 让代码生效
   codeinstyletag:function(){
    return `<style>${this.code}</style>`
   }
  },
  methods:{
   //每次打字到最底部,就要滚动
   gobottom(){
    this.$refs.container.scrolltop = 10000;
   },
   //代码修改之后,可以重新生效
   updatecode(e){
    this.$emit('update:code',e.target.textcontent);
   }
  }
 }
</script>
<style scoped>
 .code{
  display:none;
 }
</style>

新建一个 resumeeditor.vue 组件,代码如下:

<template>
 <div class = "resumeeditor" :class="{htmlmode:enablehtml}" ref = "container">
  <div v-if="enablehtml" v-html="result"></div>
  <pre v-else>{{result}}</pre>
 </div>
</template>
<script>
 import marked from 'marked'
 export default {
  props:['markdown','enablehtml'],
  name:'resumeeditor',
  computed:{
   result:function(){
    return this.enablehtml ? marked(this.markdown) : this.markdown
   }
  },
  methods:{
   gobottom:function(){
    this.$refs.container.scrolltop = 10000
   }
  }
 }
</script>
<style scoped>
 .htmlmode{
  anmation:flip 3s;
 }
 @keyframes flip{
  0%{
   opactiy:0;
  }
  100%{
   opactiy:1;
  }
 }
</style>

新建一个底部导航菜单组件 bottomnav.vue ,代码如下:

<template>
 <div id="bottom">
  <a id="pause" @click="pausefun">{{ !paused ? '暂停动画' : '继续动画 ||' }}</a>
  <a id="skipanimation" @click="skipanimationfun">跳过动画</a>
  <p>
   <span v-for="(url,index) in demourl" :key="index">
    <a :href="url.url" rel="external nofollow" >{{ url.title }}</a>
   </span>
  </p>
  <div id="music" @click="musicpause" :class="playing ? 'rotate' : ''" ref="music"></div>
 </div>
</template>
<script>
 export default{
  name:'bottom',
  data(){
   return{
    demourl:[
     {url:'http://eveningwater.com/',title:'个人网站'},
     {url:'https://github.com/eveningwater',title:'github'}
    ],
    paused:false,//暂停
    playing:false,//播放图标动画
    autoplaying:false,//播放音频
    audio:''
   }
  },
  mounted(){
   
  },
  methods:{
   // 播放音乐
   playmusic(){
    this.playing = true;
    this.autoplaying = true;
    // 创建audio标签
    this.audio = new audio();
    this.audio.src = "http://eveningwater.com/project/newreact-music-player/audio/%e9%bb%84%e5%9b%bd%e4%bf%8a%20-%20%e7%9c%9f%e7%88%b1%e4%bd%a0%e7%9a%84%e4%ba%91.mp3";
    this.audio.loop = 'loop';
    this.audio.autoplay = 'autoplay';
    this.$refs.music.appendchild(this.audio);
   },
   // 跳过动画
   skipanimationfun(e){
    e.preventdefault();
    this.$emit('on-skip');
   },
   // 暂停动画
   pausefun(e){
    e.preventdefault();
    this.paused = !this.paused;
    this.$emit('on-pause',this.paused);
   },
   // 暂停音乐
   musicpause(){
    this.playing = !this.playing;
    if(!this.playing){
     this.audio.pause();
    }else{
     this.audio.play();
    }
   }
  }
 }
</script>
<style scoped>
 #bottom{
  position:fixed;
  bottom:5px;
  left:0;
  right:0;
 }
 #bottom p{
  float:right;
 }
 #bottom a{
  text-decoration: none;
  color: #999;
  cursor:pointer;
  margin-left:5px;
 }
 #bottom a:hover,#bottom a:active{
  color: #010a11;
 }
</style>

接下来是核心 app.vue 组件代码:

<template>
 <div id="app">
  <div class="main">
   <styleeditor ref="styleeditor" v-bind.sync="currentstyle"></styleeditor>
   <resumeeditor ref="resumeeditor" :markdown = "currentmarkdown" :enablehtml="enablehtml"></resumeeditor>
  </div>
  <bottomnav ref ="bottomnav" @on-pause="pauseanimation" @on-skip="skipanimation"></bottomnav>
 </div>
</template>
<script>
 import resumeeditor from './components/resumeeditor'
 import styleeditor from './components/styleeditor'
 import bottomnav from './components/bottomnav'
 import './assets/common.css'
 import fullstyle from './style.js'
 import my from './my.js'
 export default {
  name: 'app',
  components: {
   resumeeditor,
   styleeditor,
   bottomnav
  },
  data() {
   return {
    interval: 40,//写入字的速度
    currentstyle: {
     code: ''
    },
    enablehtml: false,//是否打造成html网页
    fullstyle: fullstyle,
    currentmarkdown: '',
    fullmarkdown: my,
    timer: null
   }
  },
  created() {
   this.makeresume();
  },
  methods: {
   // 暂停动画
   pauseanimation(bool) {
    if(bool && this.timer){
     cleartimeout(this.timer);
    }else{
     this.makeresume();
    }
   },
   // 快速跳过动画
   skipanimation(){
    if(this.timer){
     cleartimeout(this.timer);
    }
    let str = '';
    this.fullstyle.map((f) => {
     str += f;
    })
    settimeout(() => {
     this.$set(this.currentstyle,'code',str);
    },100)
    this.currentmarkdown = my;
    this.enablehtml = true;
    this.$refs.bottomnav.playmusic();
   },
   // 加载动画
   makeresume: async function() {
    await this.writeshowstyle(0)
    await this.writeshowresume()
    await this.writeshowstyle(1)
    await this.writeshowhtml()
    await this.writeshowstyle(2)
    await this.$nexttick(() => {this.$refs.bottomnav.playmusic()});
   },
   // 打造成html网页
   writeshowhtml: function() {
    return new promise((resolve, reject) => {
     this.enablehtml = true;
     resolve();
    })
   },
   // 写入css代码
   writeshowstyle(n) {
    return new promise((resolve, reject) => {
     let showstyle = (async function() {
      let style = this.fullstyle[n];
      if (!style) return;
      //计算出数组每一项的长度
      let length = this.fullstyle.filter((f, i) => i <= n).map((it) => it.length).reduce((t, c) => t + c, 0);
      //当前要写入的长度等于数组每一项的长度减去当前正在写的字符串的长度
      let prefixlength = length - style.length;
      if (this.currentstyle.code.length < length) {
       let l = this.currentstyle.code.length - prefixlength;
       let char = style.substring(l, l + 1) || ' ';
       this.currentstyle.code += char;
       if (style.substring(l - 1, l) === '\n' && this.$refs.styleeditor) {
        this.$nexttick(() => {
         this.$refs.styleeditor.gobottom();
        })
       }
       this.timer = settimeout(showstyle, this.interval);
      } else {
       resolve();
      }
     }).bind(this)
     showstyle();
    })
   },
   // 写入简历
   writeshowresume() {
    return new promise((resolve, reject) => {
     let length = this.fullmarkdown.length;
     let showresume = () => {
      if (this.currentmarkdown.length < length) {
       this.currentmarkdown = this.fullmarkdown.substring(0, this.currentmarkdown.length + 1);
       let lastchar = this.currentmarkdown[this.currentmarkdown.length - 1];
       let prevchar = this.currentmarkdown[this.currentmarkdown.length - 2];
       if (prevchar === '\n' && this.$refs.resumeeditor) {
        this.$nexttick(() => {
         this.$refs.resumeeditor.gobottom()
        });
       }
       this.timer = settimeout(showresume, this.interval);
      } else {
       resolve()
      }
     }
     showresume();
    })
   }
  }
 }
</script>
<style scoped>
 #app {
  font-family: 'avenir', helvetica, arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
 }

 .main {
  position: relative;
 }

 html {
  min-height: 100vh;
 }

 * {
  transition: all 1.3s;
 }
</style>

到此为止,一个可以快速跳过动画,可以暂停动画,还有音乐播放,还能自由编辑代码的会动的简历已经完成,代码已上传至 ,欢迎 fork ,也望不吝啬 star 。

总结

以上所述是小编给大家介绍的vue.js实现会动的简历(包含底部导航功能,编辑功能),希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网