经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue.js实现会动的简历(包含底部导航功能,编辑功能)
来源:jb51  时间:2019/4/8 12:18:34  对本文有异议

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


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

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. 红色字体
  10. <style>
  11. body{
  12. color:#f00;
  13. }
  14. </style>
  15. </body>
  16. </html>

你可以狠狠点击此处 具体示例 查看效果。

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. <div id="result"></div>
  10. <script>
  11. var r = document.getElementById('result');
  12. var c = 0;
  13. var code = 'body{background-color:#f00;color:#fff};'
  14. var timer = setInterval(function(){
  15. c++;
  16. r.innerHTML = code.substr(0,c);
  17. if(c >= code.length){
  18. clearTimeout(timer);
  19. }
  20. },50)
  21. </script>
  22. </body>
  23. </html>

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. </head>
  8. <body>
  9. <div id="result"></div>
  10. <script>
  11. var r = document.getElementById('result');
  12. var c = 0;
  13. var code = 'body{background-color:#f00;color:#fff};';
  14. var timer;
  15. function write(){
  16. c++;
  17. r.innerHTML = code.substr(0,c);
  18. if(c >= code.length && timer){
  19. clearTimeout(timer)
  20. }else{
  21. setTimeout(write,50);
  22. }
  23. }
  24. write();
  25. </script>
  26. </body>
  27. </html>

你可以狠狠点击此处具体示例 查看效果。

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. <style>
  8. #result{
  9. white-space:pre-wrap;
  10. oveflow:auto;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="result"></div>
  16. <script>
  17. var r = document.getElementById('result');
  18. var c = 0;
  19. var code = `
  20. body{
  21. background-color:#f00;
  22. color:#fff;
  23. }
  24. `
  25. var timer;
  26. function write(){
  27. c++;
  28. r.innerHTML = code.substr(0,c);
  29. if(c >= code.length && timer){
  30. clearTimeout(timer)
  31. }else{
  32. setTimeout(write,50);
  33. }
  34. }
  35. write();
  36. </script>
  37. </body>
  38. </html>

你可以狠狠点击此处 具体示例 查看效果。

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>JS Bin</title>
  7. <style>
  8. #result{
  9. white-space:pre-wrap;
  10. overflow:auto;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="result"></div>
  16. <style id="myStyle"></style>
  17. <script>
  18. var r = document.getElementById('result'),
  19. t = document.getElementById('myStyle');
  20. var c = 0;
  21. var code = `
  22. body{
  23. background-color:#f00;
  24. color:#fff;
  25. }
  26. `;
  27. var timer;
  28. function write(){
  29. c++;
  30. r.innerHTML = code.substr(0,c);
  31. t.innerHTML = code.substr(0,c);
  32. if(c >= code.length){
  33. clearTimeout(timer);
  34. }else{
  35. setTimeout(write,50);
  36. }
  37. }
  38. write();
  39. </script>
  40. </body>
  41. </html>

你可以狠狠点击此处 具体示例 查看效果。

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

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5. <meta charset="UTF-8" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  8. <title>代码编辑器</title>
  9. <style>
  10. * {
  11. margin: 0;
  12. padding: 0;
  13. }
  14.  
  15. .ew-code {
  16. tab-size: 4;
  17. -moz-tab-size: 4;
  18. -o-tab-size: 4;
  19. margin-left: .6em;
  20. background-color: #345;
  21. white-space: pre-wrap;
  22. color: #f2f2f2;
  23. text-indent: 0;
  24. margin-right: 1em;
  25. display: block;
  26. overflow: auto;
  27. font-size: 20px;
  28. border-radius: 5px;
  29. font-style: normal;
  30. font-weight: 400;
  31. line-height: 1.4;
  32. font-family: Consolas, Monaco, "宋体";
  33. margin-top: 1em;
  34. }
  35.  
  36. .ew-code span {
  37. font-weight: bold;
  38. }
  39. </style>
  40. </head>
  41.  
  42. <body>
  43. <code class="ew-code">
  44. <div id="app">
  45. <p>{{ greeting }} world!</p>
  46. </div>
  47. </code>
  48. <code class="ew-code">
  49. //定义一个javascript对象
  50. var obj = {
  51. greeting: "Hello,"
  52. };
  53. //创建一个实例
  54. var vm = new Vue({
  55. data: obj
  56. });
  57. /*将实例挂载到根元素上*/
  58. vm.$mount(document.getElementById('app'));
  59. </code>
  60. <script>
  61. var lightColorCode = {
  62. importantObj: ['JSON', 'window', 'document', 'function', 'navigator', 'console', 'screen', 'location'],
  63. keywords: ['if', 'else if', 'var', 'this', 'alert', 'return', 'typeof', 'default', 'with', 'class', 'export', 'import', 'new'],
  64. method: ['Vue', 'React', 'html', 'css', 'js', 'webpack', 'babel', 'angular', 'bootstap', 'jquery', 'gulp','dom'],
  65. // special: ["*", ".", "?", "+", "$", "^", "[", "]", "{", "}", "|", "\\", "(", ")", "/", "%", ":", "=", ';']
  66. }
  67. function setHighLight(el) {
  68. var htmlStr = el.innerHTML;
  69. //匹配单行和多行注释
  70. var regxSpace = /(\/\/\s?[^\s]+\s?)|(\/\*(.|\s)*?\*\/)/gm,
  71. matchStrSpace = htmlStr.match(regxSpace),
  72. spaceLen;
  73. //匹配特殊字符
  74. var regxSpecial = /[`~!@#$%^&.{}()_\-+?|]/gim,
  75. matchStrSpecial = htmlStr.match(regxSpecial),
  76. specialLen;
  77. var flag = false;
  78. if(!!matchStrSpecial){
  79. specialLen = matchStrSpecial.length;
  80. }else{
  81. specialLen = 0;
  82. return;
  83. }
  84. for(var k = 0;k < specialLen;k++){
  85. htmlStr = htmlStr.replace(matchStrSpecial[k],'<span style="color:#b9ff01;">' + matchStrSpecial[k] + '</span>');
  86. }
  87. for (var key in lightColorCode) {
  88. if (key === 'keywords') {
  89. lightColorCode[key].forEach(function (imp) {
  90. htmlStr = htmlStr.replace(new RegExp(imp, 'gim'), '<span style="color:#00ff78;">' + imp + '</span>')
  91. })
  92. flag = true;
  93. } else if (key === 'importantObj') {
  94. lightColorCode[key].forEach(function (kw) {
  95. htmlStr = htmlStr.replace(new RegExp(kw, 'gim'), '<span style="color:#ec1277;">' + kw + '</span>')
  96. })
  97. flag = true;
  98. } else if (key === 'method') {
  99. lightColorCode[key].forEach(function (mt) {
  100. htmlStr = htmlStr.replace(new RegExp(mt, 'gim'), '<span style="color:#52eeff;">' + mt + '</span>')
  101. })
  102. flag = true;
  103. }
  104. }
  105. if (flag) {
  106. if (!!matchStrSpace) {
  107. spaceLen = matchStrSpace.length;
  108. } else {
  109. spaceLen = 0;
  110. return;
  111. }
  112. for(var i = 0;i < spaceLen;i++){
  113. var curFont;
  114. if(window.innerWidth <= 1200){
  115. curFont = '12px';
  116. }else{
  117. curFont = '14px';
  118. }
  119. htmlStr = htmlStr.replace(matchStrSpace[i],'<span style="color:#899;font-size:'+curFont+';">' + matchStrSpace[i] + '</span>');
  120. }
  121. el.innerHTML = htmlStr;
  122. }
  123. }
  124. var codes = document.querySelectorAll('.ew-code');
  125. for (var i = 0, len = codes.length; i < len; i++) {
  126. setHighLight(codes[i])
  127. }
  128.  
  129. </script>
  130. </body>
  131. </html>

你可以狠狠点击此处 具体示例 查看效果。

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

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

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

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

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

  1. <template>
  2. <div class="container">
  3. <div class="code" v-html="codeInstyleTag"></div>
  4. <div class="styleEditor" ref="container" contenteditable="true" @input="updateCode($event)" v-html="highlightedCode"></div>
  5. </div>
  6. </template>
  7. <script>
  8. import Prism from 'prismjs'
  9. export default {
  10. name:'Editor',
  11. props:['code'],
  12. computed:{
  13. highlightedCode:function(){
  14. //代码高亮
  15. return Prism.highlight(this.code,Prism.languages.css);
  16. },
  17. // 让代码生效
  18. codeInstyleTag:function(){
  19. return `<style>${this.code}</style>`
  20. }
  21. },
  22. methods:{
  23. //每次打字到最底部,就要滚动
  24. goBottom(){
  25. this.$refs.container.scrollTop = 10000;
  26. },
  27. //代码修改之后,可以重新生效
  28. updateCode(e){
  29. this.$emit('update:code',e.target.textContent);
  30. }
  31. }
  32. }
  33. </script>
  34. <style scoped>
  35. .code{
  36. display:none;
  37. }
  38. </style>

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

  1. <template>
  2. <div class = "resumeEditor" :class="{htmlMode:enableHtml}" ref = "container">
  3. <div v-if="enableHtml" v-html="result"></div>
  4. <pre v-else>{{result}}</pre>
  5. </div>
  6. </template>
  7. <script>
  8. import marked from 'marked'
  9. export default {
  10. props:['markdown','enableHtml'],
  11. name:'ResumeEditor',
  12. computed:{
  13. result:function(){
  14. return this.enableHtml ? marked(this.markdown) : this.markdown
  15. }
  16. },
  17. methods:{
  18. goBottom:function(){
  19. this.$refs.container.scrollTop = 10000
  20. }
  21. }
  22. }
  23. </script>
  24. <style scoped>
  25. .htmlMode{
  26. anmation:flip 3s;
  27. }
  28. @keyframes flip{
  29. 0%{
  30. opactiy:0;
  31. }
  32. 100%{
  33. opactiy:1;
  34. }
  35. }
  36. </style>

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

  1. <template>
  2. <div id="bottom">
  3. <a id="pause" @click="pauseFun">{{ !paused ? '暂停动画' : '继续动画 ||' }}</a>
  4. <a id="skipAnimation" @click="skipAnimationFun">跳过动画</a>
  5. <p>
  6. <span v-for="(url,index) in demourl" :key="index">
  7. <a :href="url.url" rel="external nofollow" >{{ url.title }}</a>
  8. </span>
  9. </p>
  10. <div id="music" @click="musicPause" :class="playing ? 'rotate' : ''" ref="music"></div>
  11. </div>
  12. </template>
  13. <script>
  14. export default{
  15. name:'bottom',
  16. data(){
  17. return{
  18. demourl:[
  19. {url:'http://eveningwater.com/',title:'个人网站'},
  20. {url:'https://github.com/eveningwater',title:'github'}
  21. ],
  22. paused:false,//暂停
  23. playing:false,//播放图标动画
  24. autoPlaying:false,//播放音频
  25. audio:''
  26. }
  27. },
  28. mounted(){
  29. },
  30. methods:{
  31. // 播放音乐
  32. playMusic(){
  33. this.playing = true;
  34. this.autoPlaying = true;
  35. // 创建audio标签
  36. this.audio = new Audio();
  37. 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";
  38. this.audio.loop = 'loop';
  39. this.audio.autoplay = 'autoplay';
  40. this.$refs.music.appendChild(this.audio);
  41. },
  42. // 跳过动画
  43. skipAnimationFun(e){
  44. e.preventDefault();
  45. this.$emit('on-skip');
  46. },
  47. // 暂停动画
  48. pauseFun(e){
  49. e.preventDefault();
  50. this.paused = !this.paused;
  51. this.$emit('on-pause',this.paused);
  52. },
  53. // 暂停音乐
  54. musicPause(){
  55. this.playing = !this.playing;
  56. if(!this.playing){
  57. this.audio.pause();
  58. }else{
  59. this.audio.play();
  60. }
  61. }
  62. }
  63. }
  64. </script>
  65. <style scoped>
  66. #bottom{
  67. position:fixed;
  68. bottom:5px;
  69. left:0;
  70. right:0;
  71. }
  72. #bottom p{
  73. float:right;
  74. }
  75. #bottom a{
  76. text-decoration: none;
  77. color: #999;
  78. cursor:pointer;
  79. margin-left:5px;
  80. }
  81. #bottom a:hover,#bottom a:active{
  82. color: #010a11;
  83. }
  84. </style>

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

  1. <template>
  2. <div id="app">
  3. <div class="main">
  4. <StyleEditor ref="styleEditor" v-bind.sync="currentStyle"></StyleEditor>
  5. <ResumeEditor ref="resumeEditor" :markdown = "currentMarkdown" :enableHtml="enableHtml"></ResumeEditor>
  6. </div>
  7. <BottomNav ref ="bottomNav" @on-pause="pauseAnimation" @on-skip="skipAnimation"></BottomNav>
  8. </div>
  9. </template>
  10. <script>
  11. import ResumeEditor from './components/resumeEditor'
  12. import StyleEditor from './components/styleEditor'
  13. import BottomNav from './components/bottomNav'
  14. import './assets/common.css'
  15. import fullStyle from './style.js'
  16. import my from './my.js'
  17. export default {
  18. name: 'app',
  19. components: {
  20. ResumeEditor,
  21. StyleEditor,
  22. BottomNav
  23. },
  24. data() {
  25. return {
  26. interval: 40,//写入字的速度
  27. currentStyle: {
  28. code: ''
  29. },
  30. enableHtml: false,//是否打造成HTML网页
  31. fullStyle: fullStyle,
  32. currentMarkdown: '',
  33. fullMarkdown: my,
  34. timer: null
  35. }
  36. },
  37. created() {
  38. this.makeResume();
  39. },
  40. methods: {
  41. // 暂停动画
  42. pauseAnimation(bool) {
  43. if(bool && this.timer){
  44. clearTimeout(this.timer);
  45. }else{
  46. this.makeResume();
  47. }
  48. },
  49. // 快速跳过动画
  50. skipAnimation(){
  51. if(this.timer){
  52. clearTimeout(this.timer);
  53. }
  54. let str = '';
  55. this.fullStyle.map((f) => {
  56. str += f;
  57. })
  58. setTimeout(() => {
  59. this.$set(this.currentStyle,'code',str);
  60. },100)
  61. this.currentMarkdown = my;
  62. this.enableHtml = true;
  63. this.$refs.bottomNav.playMusic();
  64. },
  65. // 加载动画
  66. makeResume: async function() {
  67. await this.writeShowStyle(0)
  68. await this.writeShowResume()
  69. await this.writeShowStyle(1)
  70. await this.writeShowHtml()
  71. await this.writeShowStyle(2)
  72. await this.$nextTick(() => {this.$refs.bottomNav.playMusic()});
  73. },
  74. // 打造成HTML网页
  75. writeShowHtml: function() {
  76. return new Promise((resolve, reject) => {
  77. this.enableHtml = true;
  78. resolve();
  79. })
  80. },
  81. // 写入css代码
  82. writeShowStyle(n) {
  83. return new Promise((resolve, reject) => {
  84. let showStyle = (async function() {
  85. let style = this.fullStyle[n];
  86. if (!style) return;
  87. //计算出数组每一项的长度
  88. let length = this.fullStyle.filter((f, i) => i <= n).map((it) => it.length).reduce((t, c) => t + c, 0);
  89. //当前要写入的长度等于数组每一项的长度减去当前正在写的字符串的长度
  90. let prefixLength = length - style.length;
  91. if (this.currentStyle.code.length < length) {
  92. let l = this.currentStyle.code.length - prefixLength;
  93. let char = style.substring(l, l + 1) || ' ';
  94. this.currentStyle.code += char;
  95. if (style.substring(l - 1, l) === '\n' && this.$refs.styleEditor) {
  96. this.$nextTick(() => {
  97. this.$refs.styleEditor.goBottom();
  98. })
  99. }
  100. this.timer = setTimeout(showStyle, this.interval);
  101. } else {
  102. resolve();
  103. }
  104. }).bind(this)
  105. showStyle();
  106. })
  107. },
  108. // 写入简历
  109. writeShowResume() {
  110. return new Promise((resolve, reject) => {
  111. let length = this.fullMarkdown.length;
  112. let showResume = () => {
  113. if (this.currentMarkdown.length < length) {
  114. this.currentMarkdown = this.fullMarkdown.substring(0, this.currentMarkdown.length + 1);
  115. let lastChar = this.currentMarkdown[this.currentMarkdown.length - 1];
  116. let prevChar = this.currentMarkdown[this.currentMarkdown.length - 2];
  117. if (prevChar === '\n' && this.$refs.resumeEditor) {
  118. this.$nextTick(() => {
  119. this.$refs.resumeEditor.goBottom()
  120. });
  121. }
  122. this.timer = setTimeout(showResume, this.interval);
  123. } else {
  124. resolve()
  125. }
  126. }
  127. showResume();
  128. })
  129. }
  130. }
  131. }
  132. </script>
  133. <style scoped>
  134. #app {
  135. font-family: 'Avenir', Helvetica, Arial, sans-serif;
  136. -webkit-font-smoothing: antialiased;
  137. -moz-osx-font-smoothing: grayscale;
  138. }
  139.  
  140. .main {
  141. position: relative;
  142. }
  143.  
  144. html {
  145. min-height: 100vh;
  146. }
  147.  
  148. * {
  149. transition: all 1.3s;
  150. }
  151. </style>
  152.  

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

在线预览

总结

以上所述是小编给大家介绍的vue.js实现会动的简历(包含底部导航功能,编辑功能),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号