gpt4 book ai didi

javascript - 从(扩展)一个 HTML 元素进行子类化?

转载 作者:太空狗 更新时间:2023-10-29 14:06:45 31 4
gpt4 key购买 nike

如果我可以创建自己的类来扩展 HTML 元素类,我会很高兴,例如HTMLDivElement 或 HTMLImageElement。

假设标准继承模式:

// class A:

function ClassA(foo) {
this.foo = foo;
}

ClassA.prototype.toString = function() {
return "My foo is " + this.foo;
};

// class B:

function ClassB(foo, bar) {
ClassA.call(this, foo);
this.bar = bar;
}

ClassB.prototype = new ClassA();

ClassB.prototype.toString = function() {
return "My foo/bar is " + this.foo + "/" + this.bar;
};

我不知道在构造函数中调用什么:

function Image2() {
// this doesn't work:
Image2.prototype.constructor.call(this);
// neither does this (only applies to <img>, no equivalent for <span> etc.):
Image.call(this);
}

Image2.prototype = new Image(); // or document.createElement("img");

Image2.prototype.toString = function() {
return "My src is " + this.src;
};

这不可能吗?或者有什么办法吗?谢谢。 =)

最佳答案

好的,这个问题需要当前技术的更新。

HTML5 为您提供了创建自定义元素的方法。您需要通过 document.registerElement 注册您的元素,然后您就可以像使用任何其他标签一样使用它。该功能已在最新的 Chrome 中可用。我不确定其他浏览器。

更多细节在这里:

http://www.html5rocks.com/en/tutorials/webcomponents/customelements/

关于javascript - 从(扩展)一个 HTML 元素进行子类化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384564/

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