跳转至

元素前后追加元素

使用 伪类 ::before::after 结合 attr 可以在元素的前后添加内容。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>测试</title>
  <style>
    body {
      background-color: #f5f5f5;
      border: 1px solid #000;
    }

    p {
      font-size: 20px;
      color: red;
      font-weight: bold;
      text-align: center;
    }

    p::before {
      content: attr(data-prefix);
      font-size: 16px;
      color: #333;
      color: blue;
    }
    p::after {
      content: attr(data-suffix);
      font-size: 16px;
      color: #333;
      color: green;
    }
  </style>
</head>

<body>
  <!-- 价格伪99.99,可以通过js截取,或者使用下面的方法都可以 -->
  <p data-prefix="¥" data-suffix=".99">99</p>
</body>
</html>

可以参考下面的做法进行价格的格式化, 或者自己通过js方法截取都可以

function processNumber(num, option=0) {
  if (option === 0) {
    // 获取整数部分
    return Math.floor(num / 100);
  } else if (option === 1) {
    // 获取小数部分(包含小数点)
    const decimal = (num / 100) - Math.floor(num / 100);
    return decimal.toFixed(2).substring(1); // 确保有两位小数并保留小数点
  } else {
    return "无效的选项,第二个参数只能是0或1";
  }
}