gpt4 book ai didi

javascript - 扩展 HTMLElement 原型(prototype)

转载 作者:行者123 更新时间:2023-11-30 11:15:40 25 4
gpt4 key购买 nike

我正在尝试扩展 main.ts 中 HTMLElement 对象的原型(prototype),以便我可以在我的整个 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"></>

我做错了什么?

我需要把这段代码放在哪里,才能让这个方法随处可用?

您是否也看到了让这段代码更简洁的可能性?

最佳答案

你需要添加一个定义为merged使用您定义要添加到 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();
});
};

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

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;

关于javascript - 扩展 HTMLElement 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51679889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com