我正在尝试用main.ts
扩展HTMLElement对象的原型,这样我就可以在我的整个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"></>
我做错了什么?
我需要把这个代码放在哪里,这样我才能让这个方法在任何地方都可用?
你是否也看到了让这段代码变得更干净的可能性?
发布于 2018-08-04 04:52:10
您需要使用定义要添加到HTMLElement
的额外函数的原始接口,添加一个定义为merged的定义
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;
https://stackoverflow.com/questions/51679889
复制相似问题