首先引入jQuery
html:
<ul> <li><a href="images/apple_1_bigger.jpg" class="tooltip" title="苹果 iPod"><img src="images/apple_1.jpg" alt="苹果 iPod" /></a></li> <li><a href="images/apple_2_bigger.jpg" class="tooltip" title="苹果 iPod nano"><img src="images/apple_2.jpg" alt="苹果 iPod nano"/></a></li> <li><a href="images/apple_3_bigger.jpg" class="tooltip" title="苹果 iPhone"><img src="images/apple_3.jpg" alt="苹果 iPhone"/></a></li> <li><a href="images/apple_4_bigger.jpg" class="tooltip" title="苹果 Mac"><img src="images/apple_4.jpg" alt="苹果 Mac"/></a></li> </ul>
JavaScript:
<script type="text/javascript"> $(function(){ var x = 10; var y = 20; $("a.tooltip").mouseover(function(e){ this.myTitle = this.title; this.title = ""; var imgTitle = this.myTitle? "<br/>" + this.myTitle : ""; var tooltip = "<div id='tooltip'><img src='"+ this.href +"' alt='产品预览图'/>"+imgTitle+"</div>"; //创建 div 元素 $("body").append(tooltip); //把它追加到文档中 $("#tooltip") .css({ "top": (e.pageY+y) + "px", "left": (e.pageX+x) + "px" }).show("fast"); //设置x坐标和y坐标,并且显示 }).mouseout(function(){ this.title = this.myTitle; $("#tooltip").remove(); //移除 }).mousemove(function(e){ $("#tooltip") .css({ "top": (e.pageY+y) + "px", "left": (e.pageX+x) + "px" }); }); }) </script>
效果图: