美文网首页
综合实例-时钟案例

综合实例-时钟案例

作者: 壹贰是只猫 | 来源:发表于2022-11-21 15:30 被阅读0次

前言:学习了,path和fs之后,需要来一个案例来操作尝试一下,以下就是本章要学习的时钟案例的相关代码

一、案例要实现的功能

将素材目录下 的index.html页面,拆分成三个文件,分别是:

  • index.css
  • index.js
  • index.html
    并且将拆分出来的3个文件,存放到dock目录中。

二、案例的实现步骤

① 创建两个正则表达式,分别用来匹配<style>和<script>标签
② 使用fs模块,读取需要被处理的HTML文件
③ 自定义resolveCSS方法,来写入index.css样式文件
④ 自定义resolveJS方法,来写入index.js脚本文件
⑤ 自定义resoleHTML方法,来写入index.html文件

步骤1 - 导入需要的模块并创建正则表达式
// 导入fs模块
const fs = require('fs')

//导入path模块
const path = require('path')

//匹配<style></style>标签的正则
//  其中 \s 表示空白字符; \S 表示非空白字符; *表示匹配任意次
const regStyle = /<style>[\s\S]*<\/style>/

//匹配<script></script>标签的正则
 const regScript= /<script>[\s\S]*<\/script>/

ps: \s 表示空白字符; \S 表示非空白字符; *表示匹配任意次 (一个大写s,一个小写s)

总结:正则表达式,我就不再这里赘述了,如果有不了解这一块的小伙伴可以等我专门出一个板块去介绍正则或者是去网上自我了解一下。给个传送门:https://www.cnblogs.com/fozero/p/7868687.html

步骤2 - 使用fs模块读取需要被处理的html文件
//调用fs.readFile()方法读取文件
fs.readFile(path.join(__dirname, './index.html'), 'utf8', function (err, dataStr) {
  //读取HTML文件失败
  if (err) return console.log('读取HTML文件失败!', +err.message)
  //读取文件成功后,调用对应的三个方法,分别拆解出css,js,html文件
  resolveCss(dataStr)
  resolveJS(dataStr)
 resolveHTML(dataStr)
})

总结:读取文件只需要用到fs.readFile()方法即可,要将读取到文件的内容通过三个方法,依次分解出css,js,html部分,这里调用的三个方法,具体实现过程会在下面具体列出。

步骤3 - 自定义resolveCSS方法
//定义处理css样式的方法
function resolveCss(htmlStr) {
  //使用正则提取需要的内容
  const r1 = regStyle.exec(htmlStr)
  //将提取出来的样式字符串,进行字符串的 replace 的替换操作
  const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
  //调用fs.writeFile()方法,将提取的样式,写入到clock目录中的index.css的文件里面
  fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function (err) {
    if (err) return console.log('写入CSS样式失败!' + err.message)
    console.log('写入样式文件成功')
  })
}

拓展:exec() 方法用于检索字符串中的正则表达式的匹配,该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。因为返回的是数组,数组的第一个,才是我们想要拿到的值,此时,我们要写入进文件的内容肯定是不能包括style标签的,所以就需要将标签替换掉,再将文件写入,就能拿到css的文件了。

以防有童鞋依旧不明白exec() 方法,再次单独举例:
语法:reg.exec(str);

var reg = /(t)(e)(s)(t)/;//把test的每个字符都用小括号包起来
var str = 'abcdtestString';
var result = reg.exec(str);//现在result就变成[“test”,”t”,”e”,”s”,”t”]
alert(result);//弹出  test,,t,e,s,t

所以取数组中的第一个,才是拿到的全部内容

步骤4 - 自定义resolveJS方法
//定义处理js脚本的方法
function resolveJS(htmlStr) {
  //通过正则,提取对应的<script></script>标签内容
  const r2 = regScript.exec(htmlStr)
  //将提取出来的内容,做进一步的处理
  const newJS = r2[0].replace('<script>', '').replace('</script>', '')
  //将处理的结果,写入到clock目录中的index.js文件里面
  fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function (err) {
    if (err) return console.log('写入JavaScript脚本失败!' + err.message)
    console.log('写入JS脚本成功')
  })
}

总结:和写入style标签的写法一样,使用正则匹配对应的script标签里面的内容,写入对应的index.js文件。

步骤5 - 自定义resolveHTML方法
//定义处理HTML结构的方法
function resolveHTML(htmlStr) {
  //将字符串调用replace方法,把内嵌的style和script标签,替换为外联的link和script标签
  const newHTML = htmlStr.
  replace(regStyle, '<link rel="stylesheet" href="./index.css" />').
  replace(regScript, '<script src="./index.js"></script>')
  //写入index.html这个文件
  fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function (err) {
    if (err) return console.log('写入HTML文件失败!' + err.message)
    console.log('写入HTML页面成功')
  })
}

分析:作为html文件,只需要将style和script部分替换为文件插入即可,然后再生成新的index.html文件。

步骤6 - 验证是否可行

通过前五个步骤,我们的clock文件已经全部生成完毕了,要想验证正确的话,就需要再index.html文件运行起来,如果和原本的html文件效果一致,即为成功。

注意点

fs.writeFile()方法只能用来创建文件,不能用来创建路径
ps:意思就是说,如果clock没有创建的话,直接node运行,fs.writeFile()是不会自己去创建clock文件夹的,因为它只能创建文件,所以就需要自己创建好文件夹,再node运行,不然是会报错滴。
重复调用fs.writeFile()写入同一个文件,新写入的内容会覆盖之前的旧内容

总结

回顾:步骤一的时候,将style标签和script标签内所有的东西范围圈了起来。步骤二,读取文件,并将index.html里面的内容全部拿到。第三步,调用resolveCSS方法,去替换拿到style标签里面的内容并存放进新的css文件内,第四步,调用resolveJS方法,去替换拿到script标签里面的内容并存放进新的js文件内。第五步,调用resolveHTML方法,去替换原本的style和script里面的内容,并改为link标签,引入前两步生成的文件。第六步,验证效果,运行html文件即可。

其实这个案例是非常简单的,也就是用到了正则会稍微有点难理解,其实就是完成了一个拆分,将js和style分离出html文件,通过link去引入,运用到的技术也是前面所讲到的,fs和path,下面我会放上效果图和index.html的源码,希望大家理解了,也可以去亲自尝试一下,那么本文到这里也就结束了,感谢观看,最后给大家推荐歌曲《或许》

成品图
<!DOCTYPE html>
<html lang="en">

<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>index首页</title>
  <style>
    html,
    body {
      margin: 0;
      padding: 0;
      height: 100%;
      background-image: linear-gradient(to bottom right, red, gold);
    }

    .box {
      width: 400px;
      height: 250px;
      background-color: rgba(255, 255, 255, 0.6);
      border-radius: 6px;
      position: absolute;
      left: 50%;
      top: 40%;
      transform: translate(-50%, -50%);
      box-shadow: 1px 1px 10px #fff;
      text-shadow: 0px 1px 30px white;

      display: flex;
      justify-content: space-around;
      align-items: center;
      font-size: 70px;
      user-select: none;
      padding: 0 20px;

      /* 盒子投影 */
      -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2)));
    }
  </style>
</head>

<body>
  <div class="box">
    <div id="HH">00</div>
    <div>:</div>
    <div id="mm">00</div>
    <div>:</div>
    <div id="ss">00</div>
  </div>
  <script>
    window.onload = function () {
      // 定时器,每隔 1 秒执行 1 次
      setInterval(() => {
        var dt = new Date()
        var HH = dt.getHours()
        var mm = dt.getMinutes()
        var ss = dt.getSeconds()

        // 为页面上的元素赋值
        document.querySelector('#HH').innerHTML = padZero(HH)
        document.querySelector('#mm').innerHTML = padZero(mm)
        document.querySelector('#ss').innerHTML = padZero(ss)
      }, 1000)
    }

    // 补零函数
    function padZero(n) {
      return n > 9 ? n : '0' + n
    }
  </script>
</body>

</html>

相关文章

网友评论

      本文标题:综合实例-时钟案例

      本文链接:https://www.haomeiwen.com/subject/mgabxdtx.html