jquery插件制作 提示框插件实现代码


  本文标签:提示框

我们首先来介绍自定义选择器的开发,他的代码结构如下:
复制代码 代码如下:

(function ($) {
$.expr[:].customselector = function (object,index,properties,list) {
//code
};
})(jQuery);

调用时候的写法:
$(a:customselector)  现在我们先解释下函数中所使用到的各个参数 。
  object:当前dom元素的引用,而不是jquery对象 。需要强调的一点,dom元素和jquery对象完全不是一回事,a标签代表的是dom元素,$(a)代表的是jquery对象,他本身是个js对象 。不清楚的朋友情google相关知识 。
  index:下标为0的数组索引 。
  properties:选择器元数据数组 。
  list:dom元素数组 。
  这些参数中,第一个参数是必须的,其他几个参数是可选的 。
  选择器函数通过bool值确定是否包含当前元素,true包含,false不包含 。
  这里我们实现一个a标签的选择器,只选择指向外部链接的a标签,代码如下:
复制代码 代码如下:

(function ($) {
$.expr[:].external = function (object) {
if ($(object).is(a)) {
return object.hostname != location.hostname;
}
};
})(jQuery);

现在我们开始实现提示框插件的开发,开发过程就不多讲了,主要是代码实现,里面有备注说明 。
复制代码 代码如下:

(function ($) {//更新坐标位置
$.fn.updatePosition = function (event) {
return this.each(function () {
$(this).css({
left: event.pageX + 20,
top: event.pageY + 5
});
});
}
//提示框插件,将显示a标签title属性的内容
$.fn.tooltip = function () {
return this.each(function () {
//获取当前对象
var self = $(this);
//获取title属性值
var title = self.attr(title);
//判断当前对象是否是a标签,title属性有无内容
if (self.is(a) && title != ) {
self.removeAttr(title)
.hover(function (event) {
//鼠标在目标对象上
$(<div id="tooltip"></div>).appendTo(body)
.text(title)
.hide()
.updatePosition(event)
.fadeIn(400);
}, function () {
//鼠标移出
$(#tooltip).remove();
}).mousemove(function (event) {
//鼠标移动
$(#tooltip).updatePosition(event);
});
}
});
};
})(jQuery);

希望本片文章对你有用,想看完整效果的朋友可以去下demo,下载地址:jQuery.plugin.tooltip