本文主要是介绍jQuery实例: ToolTip的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
转自:http://www.cnblogs.com/QLeelulu/archive/2008/03/09/1097368.html
Tooltip的插件网上很多,这里主要是通过一个简单的实例来学习jQuery.
注:本实例需要jQuery框架.
先看一下实现后的效果:
鼠标放上来看看 我的Flash站
下面让我们开始,首先,我们需要一个CSS来定义我们的显示效果:























这个CSS的效果大概是这样的:
然后就开始写我们的JS.首先要在我们的想要显示Tooltip的地方动态插入一个DIV.在这里,我将会在具有"myTip"属性的元素上显示Tooltip,并将"myTip"属性的值作为显示内容显示出来.例如我们的目标元素就好像这样:
所以我们的jQuery代码如下:











$("[myTip]") 的意思是找到文档中含有"myTip"属性的所有元素,这个是CSS表达式.jQuery的选择器还是很强的,建议多看它的文档.
我们看到上面有个 hover(function(){},function(){}) 的事件,其中第一个function()是鼠标悬停(hover)的时候会触发的,而后面一个function() 则在鼠标离开当前元素后触发.
$('<div id="luluTip"><div class="triangle" /></div>').insertAfter(this) 的意思是动态的创建一个'<div id="luluTip"><div class="triangle" /></div>'的元素并将它插入到当前元素的后面.
然后我们在该动态创建的DIV中显示我们想要显示的内容,该显示内容就是我们目标元素上"myTip"属性的值.我们可以通过$(this).attr("myTip")来获取"myTip"属性的值.在这里我们用的$(this)而不是this.因为$(this)返回的是jQuery对象,而this返回的是DOM对象.jQuery对象才具有attr("myTip")方法.然后我们用 prepend() 将该要显示的内容插入到我们刚才动态创建的DIV中.
因为我们在CSS中将改DIV定义为不可见的,所以最后我们要将它设置为可见的,我们通过设置CSS来实现:
css({"display":"block"});
在我们的鼠标离开当前元素后我们动态创建添加进来的DIV并没有用了并且还有碍地方,所以我们用remove()将它移除掉.当然在这里你可以加一个动态的效果,例如:
$( this ).remove();
});
好,接下来我们我们要实现鼠标移动的时候我们的Tooltip跟随鼠标移动的效果.
首先我们加一个mousemove的函数.这就是JS中的onmousemove,在jQuery中所有的事件函数命名都将前面的on去掉的.
然后,我们就要想办法获取鼠标的坐标.在这里我们需要声明一个evnet对象.不论何时你移动鼠标/点击/按键等等,会对应一个event的事件.在IE里event是全局变量,会被存储在window.event里.在firefox中,或者其他浏览器,event事件会被相应的自定义函数获取.所以我们取得event对象的函数如下:
e = e || window.event;
});
(e = e || window.event) 让e在所有浏览器下都能获取到event事件的对象.在Firefox下"||window.event"将不起作用,因为e已经有了赋值.在MSIE下e则是空的,所以e将被赋值为window.event.
然后我们就可以很简单的获取到鼠标的坐标位置,最后完整的代码如下:


















在这里要注意一下e.pageX和e.clientX的区别和在不同浏览器下的区别.这里不做详细分析了,有兴趣的自己搜索相关的文章看看.
Enjoy!
这篇关于jQuery实例: ToolTip的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!