首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >扩展HTMLElement原型

扩展HTMLElement原型
EN

Stack Overflow用户
提问于 2018-08-04 04:44:25
回答 1查看 1.6K关注 0票数 4

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

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

代码语言:javascript
复制
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();
  });
};

代码语言:javascript
复制
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);
代码语言:javascript
复制
#circle {
  height: 100px;
  width: 100px;
  margin: 50px;
  border-radius: 50%;
  background-color: #0f477f;
 }
代码语言:javascript
复制
<div id="circle"></>

我做错了什么?

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-04 04:52:10

您需要使用定义要添加到HTMLElement的额外函数的原始接口,添加一个定义为merged的定义

代码语言:javascript
复制
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();
    });
};

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

代码语言:javascript
复制
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;
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51679889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档