相关疑难解决方法(0)

如何创建扩展类自定义元素的新实例

我正在尝试从谷歌开发者网站的例子,我得到错误:"TypeError:非法的构造函数.有什么问题,如何解决它?

class FancyButton extends HTMLButtonElement {
  constructor() {
    super(); // always call super() first in the ctor.
    this.addEventListener('click', e => this.drawRipple(e.offsetX,e.offsetY));
  }

  // Material design ripple animation.
  drawRipple(x, y) {
    let div = document.createElement('div');
    div.classList.add('ripple');
    this.appendChild(div);
    //    div.style.top = `${y - div.clientHeight/2}px`;
    //    div.style.left = `${x - div.clientWidth/2}px`;
    div.style.backgroundColor = 'currentColor';
    div.classList.add('run');
    div.addEventListener('transitionend', e => div.remove());
  }
}

customElements.define('fancy-button', FancyButton, {extends: 'button'});
let button = new FancyButton();
button.textContent = 'Fancy button!';
button.disabled = true;
Run Code Online (Sandbox Code Playgroud)

html javascript web-component ecmascript-6 custom-element

8
推荐指数
2
解决办法
3384
查看次数

扩展 HTMLButtonElement 的 WebComponent 未调用 constructor() 和connectedCallBack()

我正在尝试创建一个Web 组件 button,但是当我将其添加到 HTML 中时,该constructor()函数永远不会被调用。

class MyButton extends HTMLButtonElement {
  title = "";
  constructor({ title }) {
    super();
    this.title = title;
    this.addEventListener("click", (e) => this.rippe(e.offsetX, e.offsetY));
  }

  rippe(x, y) {
    let div = document.createElement("div");
    div.classList.add("ripple");
    this.appendChild(div);
    div.style.top = `${y - div.clientHeight / 2} px`;
    div.style.left = `${x - div.clientWidth / 2} px`;
    div.style.backgroundColor = "currentColor";
    div.classList.add("run");
    div.addEventListener("transitioned", (e) => div.remove());
  }

  connectedCallback() {
    this.innerHTML = this.title;
  }
}
window.customElements.define("my-button", MyButton, { extends: "button" });
Run Code Online (Sandbox Code Playgroud)
my-button { …
Run Code Online (Sandbox Code Playgroud)

html javascript web-component

5
推荐指数
1
解决办法
709
查看次数

扩展 HTMLSpanElement 时“未捕获类型错误:非法构造函数。”

我得到一个Uncaught TypeError: Illegal constructor.基本上空的构造函数:

export class Citation extends HTMLSpanElement {
  constructor() {
    super();
  }
}
Run Code Online (Sandbox Code Playgroud)

这个有用的答案中的评论声称

我在使用 Web 组件时遇到了同样的错误,但仅限于 Safari(不是 Firefox)。原因是我做了一个 UserAvatar 类扩展 HTMLSpanElement (而不是 HTMLElement)

这让我尝试了一下HTMLElement,这实际上消除了错误。所以现在我想知道。我可以扩展哪些 HTML 元素?为什么我不能扩展span元素?还有几个类似的问题:Uncaught TypeError: Illegal constructor whenextending HTMLButtonElementHow to create new instance of an Extended Class of Custom elements。但它们有点旧,在这个答案中声称这应该从 2018 年 10 月开始工作。我使用的是最新的 Firefox 浏览器,所以我很困惑......

有人知道发生了什么事吗?

javascript web-component

3
推荐指数
1
解决办法
3345
查看次数