时间:2014-01-29所属栏目: Jquery开发 来源: 热度:
虽然已经有很多的工具提示插件,但却很少去解释提示插件的工作逻辑,今天我为大家分享我的创建方法,欢迎任何的批评和建议。
为了尽可能的简单但有保持足够的灵活性。主要的链接将用"tip_trigger"来触发提示,类名"tip"是提示的内容。
<a href="#" class="tip_trigger"> Your Link Key Word <span class="tip">This will show up in the tooltip</span> </a>
这个样式设置相当简单,当然,我也鼓励你们为这个项目添加创意。tooltip默认是隐藏的,通过Jquery触发。我将提示内容设置为绝对定位,指定z-index:1000,确保它在元素的上层停留。
.tip {
color: #fff;
background:#1d1d1d;
display:none; /*--Hides by default--*/
padding:10px;
position:absolute; z-index:1000;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
对于那些不熟悉使用jQuery,你先看看他们的网站并获得了它是如何工作的概述。
//Tooltips
var tip = null;
$(".tip_trigger").hover(function(){
//缓存工具提示,并把它从内容块中删除,并把它应用到body
tip = $(this).find('.tip').remove();
$('body').append(tip);
tip.show(); //显示工具提示
}, function() {
tip.hide().remove(); //隐藏并移除body中的工具提示
$(this).append(tip); //返回原来的位置
}).mousemove(function(e) {
//console.log(e.pageX)
if ( tip == null ) return;
var mousex = e.pageX + 20; //获取鼠标在文档的X值加20
var mousey = e.pageY + 20; //获取鼠标的Y值加20
var tipWidth = tip.width(); //.tip的宽度
var tipHeight = tip.height(); //.tip的高度
//计算.tip距离右边缘的位置
var tipVisX = $(window).width() - (mousex + tipWidth);
var tipVisY = $(window).height() - (mousey + tipHeight);
if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
mousex = e.pageX - tipWidth - 20;
$(this).find('.tip').css({ top: mousey, left: mousex });
} if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
mousey = e.pageY - tipHeight - 20;
tip.css({ top: mousey, left: mousex });
} else {
tip.css({ top: mousey, left: mousex });
}
});
});