首页 > 解决方案 > 扩展 HTMLElement 原型

问题描述

我正在尝试扩展 HTMLElement 对象的原型main.ts,以便我可以在整个 Angular 6 项目中使用它。

但我得到Property 'fadeOut' does not exist on type 'HTMLElement'.

HTMLElement.prototype.fadeOut = function(duration: number = 300): Promise<void> {
  const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
  return new Promise(resolve => {
    const animation: Animation = this.animate(keyframes, duration);
    animation.onfinish = () => resolve();
  });
};

const circle = document.getElementById('circle');

HTMLElement.prototype.fadeOut = function(duration = 300) {
  const keyframes = [{ opacity: 1 }, { opacity: 0 }];
  return this.animate(keyframes, duration).finished
};

circle.fadeOut(2000);
#circle {
  height: 100px;
  width: 100px;
  margin: 50px;
  border-radius: 50%;
  background-color: #0f477f;
 }
 
<div id="circle"></>

我究竟做错了什么?

我需要把这段代码放在哪里,这样我才能让这个方法在任何地方都可用?

你是否也看到了让这段代码更干净的可能性?

标签: javascriptangulartypescript

解决方案


您需要添加一个定义以与您定义要添加到的额外功能的原始界面合并HTMLElement

interface HTMLElement {
    fadeOut(duration: number): Promise<void>
}

// Will now work 
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};

如果代码在模块中,则需要在全局命名空间中声明接口

declare global {
    interface HTMLElement {
        fadeOut(duration: number): Promise<void>
    }

}
HTMLElement.prototype.fadeOut = function (duration: number = 300): Promise<void> {
    const keyframes: AnimationKeyFrame[] = [{ opacity: 1 }, { opacity: 0 }];
    return new Promise(resolve => {
        const animation: Animation = this.animate(keyframes, duration);
        animation.onfinish = () => resolve();
    });
};


export var x;

推荐阅读