我有一个函数接受元素作为参数,这个元素将用于执行函数内部的操作.
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);
Run Code Online (Sandbox Code Playgroud)
这里元素作为参数传递.但我不想这样做.是否可以创建一个将在元素上调用的函数?例
element.center();
Run Code Online (Sandbox Code Playgroud)
您还可以考虑jQuery函数,如:$(element).next();
等.
注意我不想使用jQuery.我需要纯粹的JavaScript编码.
通过使用jQuery,可以通过在下面创建
中心功能
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;
};
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
这将允许您.center()
在任何节点上调用.
注意:定义原型函数时,this
是调用函数的对象(在本例中为Node).