gpt4 book ai didi

javascript - 如何在 HTML 元素上创建函数而不是将元素作为参数传递

转载 作者:行者123 更新时间:2023-11-28 13:25:36 24 4
gpt4 key购买 nike

我有一个接受元素作为参数的函数,该元素将用于在函数内执行操作。

function center(element) {
// code to align this given element to center position
element.css("position","fixed");
element.css("top", Math.max(0, ((window.innerHeight - element[0].offsetHeight) / 2))+ "px");
element.css("left", Math.max(0, ((window.innerWidth - element[0].offsetWidth) / 2))+ "px");
return element;
}

// calling above function
center(element);

这里元素作为参数传递。但我不想那样做。是否可以创建一个将在元素上调用的函数?示例

element.center();

您还可以考虑 jQuery 函数,例如:$(element).next(); 等。

注意我不想使用 jQuery。我需要纯 JavaScript 编码。

通过使用 jQuery,可以通过下面的创建来实现

center function

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.height()) / 2) + $(window).scrollTop())+ "px");
this.css("left", Math.max(0, (($(window).width() - this.width()) / 2) + $(window).scrollLeft())+ "px");
return this;
};

最佳答案

您可以将函数添加到 prototype Node的对象:

Node.prototype.center = function() {
// code to align this given element to center position
this.css("position","fixed");
this.css("top", Math.max(0, ((window.innerHeight - element[0].offsetHeight) / 2))+ "px");
this.css("left", Math.max(0, ((window.innerWidth - element[0].offsetWidth) / 2))+ "px");
return this;
}

这将允许您在任何节点上调用 .center()

注意:定义原型(prototype)函数时,this 是调用该函数的对象(在本例中为 Node)。

关于javascript - 如何在 HTML 元素上创建函数而不是将元素作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29504841/

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