html

  • html
  • html
About 9 min

html

自定义属性 data-*

html标签自定义属性 data-* 可以用来保存 一些与不同DOM元素相关联的信息 。 自定义属性可以设置多个

如下:

<li id="id"  data-num="1"  data-names="zhangsan"  data-age="999">
  Hello world
</li>

使用 js 获取自定义属性

1 使用 getAttribute 和 setAttribute

var restaurant = document.getElementById("id");
var strings = restaurant.getAttribute("data-num");
var restaurant = document.getElementById("id");
restaurant.setAttribute("data-num", "dataNum");

2 使用dataset属性

var restaurant = document.getElementById("id");

var stringss = restaurant.dataset.num;   // 通过dataset获取自定义属性
restaurant.dataset.num = newNum;         //  设置自定义属性的值

table表格设置边线为单边线

css border-collapse属性

border-collapse:属性,为表格设置合并边框模型。 其属性值如下: separate:默认值。边框会被分开。 collapse:将边框会合并为一个单线的边框 inherit:继承父元素的 border-collapse 属性的值,早期IE浏览器不支持此值。 实现 table 的单线边框的办法 为 table 表格的样式,为入 border-collapse 属性即可

   <table>
        <tr>
            <td>内容</td>
            <td>内容</td>
            <td>内容</td>
        </tr>
        <tr>
            <td>内容</td>
            <td>内容</td>
            <td>内容</td>
        </tr>
        <tr>
            <td>内容</td>
            <td>内容</td>
            <td>内容</td>
        </tr>
    </table>
    
    <style>
    	    table,table tr td { 
                border:1px solid #ccc; 
                 border-collapse:collapse
            }
            table tr td{
                padding: 5px 10px;
            }
    </style>

input 上传文件

<input type="file" onchange="uploadFile" />

const uploadFile = (e) => {
  let reader = new FileReader();
  reader.readAsDataURL(e.target.files[0]);  // 传递参数 e.target.files[0]  ,后台用MultipartFile接收实现上传文件
  // reader.readAsText(e.target.files[0])  //读取text文件内容
  reader.onload = (e) => {
    console.log(e.target.result); //读取内容
  };
};

FileReader 对象是 Web API 的一部分,它提供了几种方法来读取文件,并将文件内容转换为 JavaScript 可以使用的格式。以下是 FileReader 的主要方法:

  1. readAsArrayBuffer(file)
    • 读取文件的内容,并将其作为 ArrayBuffer 对象返回。这对于处理二进制文件(如图像或音频文件)非常有用。
  2. readAsBinaryString(file)
    • 读取文件的内容,并将其作为二进制字符串返回。这个方法在现代浏览器中已经不推荐使用,因为它的性能较差。
  3. readAsDataURL(file)
    • 读取文件的内容,并将其作为 data URL 返回。这对于在网页上直接显示图像或视频等媒体内容非常有用。
  4. readAsText(file, [encoding])
    • 读取文件的内容,并将其作为文本字符串返回。可以指定一个可选的编码参数,通常用于非 UTF-8 编码的文本文件。如果不指定编码,默认使用 UTF-8 编码。

每个方法都会触发 FileReaderonload 事件,当文件读取完成后,可以通过 e.target.result 访问读取的内容。如果读取过程中发生错误,会触发 onerror 事件。如果用户在读取完成前取消了文件读取,会触发 onabort 事件。

ul li 去除前面的黑点

ul {
      list-style-type: none;
}
list-style-type: "123";   ""里面的内容展示在 li 标签前面

//  list-style-type 常用属性值有以下几个
1 none不使用项目符号    
2 disc实心圆,默认值    
3 circle空心圆    
4 square实心方块    
5 decimal阿拉伯数字    
6 lower-roman小写罗马数字    
7 upper-roman大写罗马数字    
8 lower-alpha小写英文字母    
9 upper-alpha大写英文字母

audio video

audio用于在文档中表示用品内容,比如音乐。``可以包含多个音频资源,使用src或者source属性进行描述,浏览器会选择最合适的来用。当前它只支持三种音频格式:MP3, WAV, and OGG。

https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/audioopen in new window

<audio controls>
  <!-- Won't play because the mp3 doesn't exist -->
  <source src="cat.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>
对于不考虑兼容问题时,可以直接将src设置在 audio 标签里
<audio controls src="horse.mp3">

Video用来处理电影或者视频流。这个可能是大家最熟悉的标签之一了。它现在支持的视频格式包括: MP4, WebM, and Ogg 。

https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/videoopen in new window

<video width="320" height="240" controls>
  <source src="movie.mp4"  type="video/mp4">
  <source src="movie.ogg"  type="video/ogg">
  您的浏览器不支持 HTML5 video 标签。
</video>

对于不考虑兼容问题时,可以直接将src设置在video标签里

<video width="320" height="240" controls src="movie.mp4"></video>

progress 进度条

<progress id="file" max="100" value="70"> 70% </progress>

details 标签 挂件(实现下拉展示)

details可以创建一个挂件,默认处于关闭状态,仅在被切换成展开状态时才会显示隐藏的内容信息。可以在其中嵌入summary标签,为该部件提供概要。

<details>
  <summary>总结</summary>
  <!-- 非必填,默认显示“详细信息” -->
  我是内容,我是内容。我是内容,我是内容。我是内容,我是内容。
</details>

Template

Template用来包含一些在页面加载时不会呈现的内容,但随后可以在运行时使用javascript进行实例化。

可以用来存储一段后续要用到的内容片段,减少了在JavaScript实例化节点时创建模版内容的过程。

<template>
  <h2>前端记事本</h2>
  <p>前端记事本前端记事本</p>
</template>

在javascript中可以使用这部分模版来实例化节点

function createNewNode() {
  const node = document.querySelector('template');
  const template = node.content.cloneNode(true);
  document.body.appendChild(template);
}

img

造数据时,将本地图片转 url

img:   new URL("@/assets/images/index/zph1.png", import.meta.url),

相关技术文章

分享24个强大的HTML属性,建议每位前端工程师都应该掌握! (qq.com)open in new window

canvas

Canvas API - Web API | MDN (mozilla.org)open in new window

基础绘制

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="text/javascript">
      function draw() {
        let canvas = document.getElementById("tutorial"); //  获取 canvas 元素
        if (canvas.getContext) {
          var ctx = canvas.getContext("2d"); //  getContext() 方法来访问绘画上下文

          ctx.fillStyle = "rgb(200,0,0)"; // 绘制图形
          ctx.fillRect(10, 10, 55, 50);

          ctx.font = "20px serif"; // 设置字体样式
          ctx.fillText("Hello world", 10, 80); // 绘制文字填充(显示fillStyle的样式)
          ctx.strokeText("Hello world", 10, 100); // 绘制文字边框

          draw2();
        }
      }
      <!-- 运动元素 -->
      function draw2() {
        let canvas = document.getElementById("tutorial"); //  获取 canvas 元素
        if (canvas.getContext) {
          var ctx = canvas.getContext("2d"); //  getContext() 方法来访问绘画上下文
          ctx.strokeText("Hello", 10, 120); // 绘制文字边框
          ctx.translate(5, 0);       // 位移
          window.requestAnimationFrame(draw2);  // 递归调用,循环渲染
        }
      }
    </script>
    <style type="text/css">
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body onload="draw();">
    <canvas id="tutorial" width="600" height="400">
      标签里面的内容会在浏览器不支持 canvas 标签时显示。
    </canvas>
  </body>
</html>

简易烟花绽放效果

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>全屏持续烟花效果</title>
<style>
  /* 设置页面和画布样式 */
  body, html {
    margin: 0;
    padding: 0;
    overflow: hidden;
    height: 100%;
    background-color: black; /* 背景颜色为黑色,模拟夜空 */
  }
  canvas {
    display: block; /* 确保canvas元素独占一行 */
  }
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
  // 获取canvas元素和上下文
  const canvas = document.getElementById('fireworksCanvas');
  const ctx = canvas.getContext('2d');

  // 设置画布尺寸为全屏,并在窗口大小改变时重新调整
  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }
  window.onresize = resizeCanvas;
  resizeCanvas(); // 初始化设置

  // 定义粒子类,用于表示烟花爆炸后产生的小点
  class Particle {
    constructor(x, y, vx, vy) {
      this.x = x; // 粒子的x坐标
      this.y = y; // 粒子的y坐标
      this.vx = vx; // 水平速度
      this.vy = vy; // 垂直速度
      this.alpha = 1; // 不透明度,用于控制粒子逐渐消失的效果
    }

    // 更新粒子的位置和属性
    update() {
      this.x += this.vx;
      this.y += this.vy;
      this.vy += 0.1; // 加重力,使粒子加速下落
      this.alpha -= 0.03; // 减少不透明度,模拟粒子渐渐消失
    }

    // 绘制粒子
    draw() {
      ctx.globalAlpha = this.alpha; // 设置全局透明度
      ctx.fillStyle = 'hsla(' + (this.x % 360) + ', 100%, 50%, ' + this.alpha + ')'; // 使用HSLA颜色模式,增加视觉多样性
      ctx.beginPath();
      ctx.arc(this.x, this.y, 2, 0, Math.PI * 2); // 绘制圆形粒子
      ctx.fill(); // 填充绘制的路径
    }
  }

  // 定义烟花类,用于表示一个完整的烟花,包括上升和爆炸过程
  class Firework {
    constructor() {
      this.x = Math.random() * canvas.width; // 随机水平位置
      this.y = canvas.height; // 烟花从底部出发
      this.targetY = Math.random() * (canvas.height * 0.4) + canvas.height * 0.1; // 随机目标高度,范围在屏幕高度的10%到50%
      this.vy = -Math.sqrt(2 * 9.8 * (canvas.height - this.targetY)) / 10; // 根据物理公式计算初始速度,适当调整系数以适应新的高度
      this.particles = []; // 存储爆炸后的粒子
      this.exploded = false; // 标记烟花是否已经爆炸
    }

    // 更新烟花的状态(上升或爆炸)
    update() {
      if (!this.exploded) {
        this.y += this.vy;
        this.vy += 0.1; // 模拟上升过程中的减速(重力加速度)
        if (this.y <= this.targetY || this.vy >= 0) { // 达到目标高度或速度变为非负数时爆炸
          this.explode();
        }
      } else {
        for (let i = this.particles.length - 1; i >= 0; i--) {
          this.particles[i].update();
          if (this.particles[i].alpha <= 0) this.particles.splice(i, 1); // 移除透明度为零的粒子
        }
      }
    }

    // 烟花爆炸,生成多个粒子
    explode() {
      this.exploded = true;
      for (let i = 0; i < 100; i++) {
        let angle = Math.random() * Math.PI * 2; // 随机角度
        let speed = Math.random() * 5 + 2; // 随机速度
        this.particles.push(new Particle(this.x, this.y, Math.cos(angle) * speed, Math.sin(angle) * speed));
      }
    }

    // 绘制烟花或其产生的粒子
    draw() {
      if (!this.exploded) {
        ctx.fillStyle = 'white';
        ctx.fillRect(this.x - 2, this.y - 2, 4, 4); // 绘制上升的火花
      } else {
        for (let particle of this.particles) {
          particle.draw();
        }
      }
    }
  }

  let fireworks = []; // 存储所有正在动画的烟花
  let lastLaunchTime = 0; // 记录上次发射烟花的时间戳
  const launchInterval = 500; // 控制烟花发射的时间间隔,单位为毫秒

  // 动画循环函数,负责更新和绘制所有烟花
  function animate(timestamp) {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除上一帧的内容

    // 以固定的时间间隔发射烟花
    if (timestamp - lastLaunchTime > launchInterval) {
      lastLaunchTime = timestamp;
      launchFirework(); // 发射一个新的烟花
    }

    for (let i = fireworks.length - 1; i >= 0; i--) {
      fireworks[i].update(); // 更新每个烟花的状态
      fireworks[i].draw(); // 绘制每个烟花或其产生的粒子
      if (fireworks[i].particles.length === 0 && fireworks[i].exploded) {
        fireworks.splice(i, 1); // 移除已完成动画的烟花
      }
    }

    requestAnimationFrame(animate); // 请求下一帧动画
  }

  // 发射烟花,创建一个新的烟花并添加到列表中
  function launchFirework() {
    fireworks.push(new Firework());
  }

  // 开始动画循环
  requestAnimationFrame(animate);
</script>
</body>
</html>

小球运动mdn示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>全屏持续烟花效果</title>
<style>
  /* 设置页面和画布样式 */
  body, html {
    margin: 0;
    padding: 0;
    overflow: hidden;
    height: 100%;
    
  }
  #fireworksCanvas{
    border: 1px solid black;
  }
  canvas {
    display: block; /* 确保canvas元素独占一行 */
  }
</style>
</head>
<body>
<canvas id="fireworksCanvas" width="500" height="500"></canvas>
<script>
  // 获取canvas元素和上下文
  const canvas = document.getElementById('fireworksCanvas');
  const ctx = canvas.getContext('2d');

  const ball = {
    x: 100,
    y: 100,
    vx: 5,
    vy: 2,
    radius: 20,
    color: "blue",
    draw() {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.fillStyle = this.color;
      ctx.fill();
    },
    changeColor(){
      if(this.color === "red"){
        this.color = "blue";
      }else{
        this.color = "red";
      }
      
    }
  };

  const draw=()=> {
    //ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

   // 现在,使用的是 clearRect 函数帮我们清除前一帧动画。若用一个半透明的 fillRect 函数取代之,就可轻松制作长尾效果。
    ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ball.changeColor()
    ball.draw();
    ball.x += ball.vx;
    ball.y += ball.vy;

    // 模拟重力效果
    ball.vy *= 0.99;
    ball.vy += 0.25;
  
    // 防止小球超出边界
    if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
      ball.vy = -ball.vy;
    }
    if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
      ball.vx = -ball.vx;
    }
  
    raf = window.requestAnimationFrame(draw);
  }
  
  canvas.addEventListener("mouseover", (e) => {
    raf = window.requestAnimationFrame(draw);
  });
  
  canvas.addEventListener("mouseout", (e) => {
    // 停止运动
    window.cancelAnimationFrame(raf);
  });

  ball.draw()
 
</script>
</body>
</html>

requestAnimationFrame的用法、优势和应用场景

作为一个前端你连requestAnimationFrame的用法、优势和应用场景都搞不清楚? (qq.com)open in new window

使用实例


<template>
  <div>
    <button @click="stop">停止</button>
  </div>
</template>
<script lang="ts" setup>
  let myReq;
  function init(val) {
    console.log('您好,requestAnimationFrame回调:', val);
    myReq = requestAnimationFrame(init);
  }
  requestAnimationFrame(init);

  function stop() {
    cancelAnimationFrame(myReq);
  }
</script>

Loading...