joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

拓展基础元素功能用法 is使用

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

<head>
  <meta charset="UTF-8">
  <link rel="icon" href="/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vite App</title>
</head>

<body>
  <div id="app"></div>

  <!-- 使用扩展的img元素 -->
  <img is="fancy-img" src="https://example.com/image.jpg" alt="示例图片">

  <script>
    // 扩展 HTMLImageElement
    class FancyImg extends HTMLImageElement {
      constructor() {
        super();

        // 添加边框样式
        this.style.border = '2px solid #333';
        this.style.borderRadius = '8px';
        this.style.padding = '4px';

        // 添加加载失败处理
        this.addEventListener('error', () => {
          this.src = '/default-image.jpg'; // 设置默认图片
          console.log('图片加载失败,已替换为默认图片');
        });
      }

      // 当元素被添加到文档时调用
      connectedCallback() {
        console.log('fancy-img 已添加到页面');
      }
    }

    // 注册自定义元素,注意第三个参数
    customElements.define('fancy-img', FancyImg, { extends: 'img' });
  </script>

  <script type="module" src="/src/main.js"></script>
</body>

</html>


自定义新元素

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

<head>
  <meta charset="UTF-8">
  <link rel="icon" href="/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vite App</title>
</head>

<body>
  <div id="app"></div>
  <hello-world name="Vue"></hello-world>

  <script>
    class HelloWorld extends HTMLElement {
      constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });

        const wrapper = document.createElement('div');
        const name = this.getAttribute('name') || 'World';

        const style = document.createElement('style');
        style.textContent = `
            .hello-world {
              background: #f0f0f0;
              padding: 10px;
              border-radius: 5px;
              font-family: Arial, sans-serif;
              color: #333;
            }
          `;

        wrapper.setAttribute('class', 'hello-world');
        wrapper.textContent = `Hello, ${name}!`;

        shadow.appendChild(style);
        shadow.appendChild(wrapper);
      }
    }

    customElements.define('hello-world', HelloWorld);
  </script>

  <script type="module" src="/src/main.js"></script>
</body>

</html>
  • 渲染效果
    image
posted on 2024-11-27 22:07  joken1310  阅读(5)  评论(0编辑  收藏  举报