允许转载,但请注明出处:http://blog.youkuaiyun.com/sysuzjz/article/details/41851711
模仿QQ空间、微博等鼠标悬浮在人名上时,显示用户详细信息
大体思路是将名片卡隐藏在页面中,当悬浮时将名片卡移动到鼠标边,鼠标移开时隐藏名片卡。
本文的JS使用了jquery
用户名跟名片卡代码如下(只是为了显示类名,具体内容按需补充):
<pre name="code" class="html"><a href="#" class="user-link" data-uid="">用户名</a>
<div class="msg-card hide"></div> JS代码如下:
var showMsgCardControl = null;
// 鼠标悬浮在用户名上时,显示名片卡,并移动到鼠标边
$(".user-link").mouseover(function(event) {
clearShowControl();
var position = getPosition(event);
var uid = $(this).data("uid");
$.ajax({
type: "post",
url: "your_backend_url",
data: {
"uid": uid
},
success: function(msg) {
showMsgCard(position);
changeMsgCard(msg);
}
})
});
// 鼠标离开用户名一定时间后,隐藏名片卡,如果在这段时间内鼠标移动至名片卡上,则取消隐藏,若再次离开名片卡一段时间,则隐藏名片卡
$(".user-link").mouseout(function(event) {
setShowControl();
});
$(".msg-card").mouseover(function(event) {
clearShowControl();
});
$(".msg-card").mouseout(function(event) {
setShowControl();
});
function changeMsgCard(msg) {
$(".msg-card").replaceWith(
'<div class="msg-card hide">' +
'</div>'
);
}
function showMsgCard(position) {
$(".msg-card").show().css({
"top": position.y,
"left": position.x
});
}
function setShowControl() {
showMsgCardControl = setTimeout(hideMsgCard, 1000);
}
function clearShowControl() {
clearTimeout(showMsgCardControl);
}
function hideMsgCard() {
$(".msg-card").hide();
}
// mouseCoord获取到的坐标为鼠标尖端,各加20以避免被鼠标挡住
function getPosition(event) {
var pos = mouseCoords(event);
return {
x: pos.x + 20,
y: pos.y + 20
};
}
// 获取当前事件(鼠标)发生的坐标
function mouseCoords(event)
{
if(event.pageX || event.pageY){
return {
x:event.pageX,
y:event.pageY
};
}
// IE不支持上面的,则会执行下面的代码
return {
x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
y:event.clientY + document.body.scrollTop - document.body.clientTop
};
};