javascript - 扩展 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"></>
我究竟做错了什么?
我需要把这段代码放在哪里,这样我才能让这个方法在任何地方都可用?
你是否也看到了让这段代码更干净的可能性?
解决方案
您需要添加一个定义以与您定义要添加到的额外功能的原始界面合并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;
推荐阅读
- ios - 如何从 Swift 中的视图访问模型中的变量
- angular - 如何让我的 Angular 应用程序与可以在 Azure 门户中按下的 b2c“撤销会话”按钮一起使用
- javascript - 最接近的元素 id JS
- python - 如何查看数据框中是否存在列名,如果不存在则使用默认值创建列?
- c# - How to refuse a response intentionally from Asp.net
- android-studio - Flutter Provider Package: error could not find correct Provider
above this LoginForm - python - 如何根据计算条件创建新列?
- java - 如何从网页中提取 id 列表?
- r - How can I change the point color in my scatter plot for each column of my dataframe (one color for each column)?
- firebase - what is Product renting firebase best approach