【发布时间】: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