【问题标题】:Custom Web Component image not showing自定义 Web 组件图像未显示
【发布时间】:2021-03-20 07:07:00
【问题描述】:

我一直在学习 Brad Traversy 的关于 Web 组件的 yt 教程,他是一位内容丰富的优秀教师,我相信你们中的许多人已经知道 :)

我已经到了 17 分钟,但我遇到的问题是图像没有像教程中那样显示...

它们正在被添加到文档流中...我可以这么说,因为布局会重新调整以适应图像的空间...只是图像没有显示...

为了比较,我直接在html中添加了一张性质相似的图片,效果很好。

无论如何,这是我的代码...

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Components Example</title>
  <style>
    h3 {
      color: purple;
    }
  </style>
</head>
<body>
  <h3>Hello World... where's the images?!?!?</h3>
  
  <!-- <user-card name="you oddo" avatar="https://randomuser.me/api/portraits/men/1.jpg"></user-card> -->

  <user-card name="huik popp" avatar="38.jpg"></user-card>

  <user-card name="som otha"></user-card>

  <img src="95.jpg">

  <style>h3 {color: green}</style>

  <script src="userCard.js"></script>
</body>
</html>

还有 Javascript... UserCard.js:

const template = document.createElement('template');
template.innerHTML = `
  <style>
    h3 {
      color: coral;
    }
  </style>
  <div class="user-card">
    <img />
    <div>
      <h3></h3>
    </div>  
  </div>
`;

class UserCard extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: 'open'});
    this.shadowRoot.appendChild(template.content.cloneNode(true));
    this.shadowRoot.querySelector('h3').innerText = this.getAttribute('name');
    this.shadowRoot.querySelector('img').innerText = this.getAttribute('avatar');
  }
}

window.customElements.define('user-card', UserCard);

对于这方面的任何帮助,我将不胜感激。到目前为止,我一直很喜欢跟着本教程一起学习,希望能跟上视频中的内容。

非常感谢。

【问题讨论】:

    标签: image custom-element createelement


    【解决方案1】:

    告诉 Brad 他可以将代码缩短为:

    class UserCard extends HTMLElement {
      constructor() {
        super()
          .attachShadow({ mode: 'open'})
          .innerHTML = `
      <style>
        h3 {
          color: coral;
        }
      </style>
      <div class="user-card">
        <img />
        <div>
          <h3></h3>
        </div>  
      </div>
    `;
    
    ...
    
      }
    );
    

    【讨论】:

      【解决方案2】:

      我在这里回答我的问题...

      在 userCard.js 中,我有:

      this.shadowRoot.querySelector('img').innerText = this.getAttribute('avatar');
      

      应该是:

      this.shadowRoot.querySelector('img').src = this.getAttribute('avatar');
      

      【讨论】:

      • 这很有趣,因为我刚刚遇到了一个类似的问题,即我的图像无法加载。但是,即使我的脚本是直接从他的工作代码笔示例中复制的,我的图像仍然无法加载,而且我只是在我同样复制的 html 页面中引用脚本。其他部分显示正常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 2011-03-02
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多