简述:
实现一个头像悬浮框
以jquery插件形式实现, 同时使用cookie json做缓存
,减少短期内hover时间连续触发,导致服务器过多请求
代码:
/** * 鼠标移动到头像后,出现弹出框 * @param obj */ function avatarOnMouseOver(obj, userId, imageUrl){ var avatarPopWindow = $("#iuyt").removeClass("hide"); $(obj).append(avatarPopWindow); callAvatarData(avatarPopWindow, userId, imageUrl); }; /** * 向后台请求人员头像的数据 */ function callAvatarData(popWin, userId, imageUrl){ // 先从cookie中寻找,如果有的话,就不再向后台去要 var userInfoStr = $.cookie(userId); if(userInfoStr != null){ var userInfo = JSON.parse(userInfoStr); setUserInfoToPopWindow(popWin, userInfo) }else{ $.ajax({ type: "post", url: '/webproj/staff/getUserInfo', dataType:"json", data: { userId: userId }, success: function(userInfo){ setUserInfoToPopWindow(popWin, userInfo) var dateNow = new Date(); var dateExpired = new Date(); dateExpired.setTime(dateNow.getTime() + (60 * 1000)); $.cookie(userId, JSON.stringify(userInfo), {expires: dateExpired}) } }); } } function setUserInfoToPopWindow(popWin,userInfo){ // 得到的数据填充人员名片 $(popWin).find("#avatarName").text(userInfo.name); $(popWin).find("#avatarIconUrl").attr('src', userInfo.iconUrl); $(popWin).find("#avatarOrganizationName").text(userInfo.organizationName); $(popWin).find("#avatarPhone").text("电话:" + userInfo.phone); $(popWin).find("#avatarMobile").text("手机:" + userInfo.mobile); $(popWin).find("#avatarEmail").text("邮箱:" + userInfo.email); $(popWin).find("#avatarCompanyName").text(userInfo.companyName); } /** * 鼠标移开后,隐藏弹出框 * @param obj */ function avatarOnMouseOut(obj){ $("#iuyt").addClass("hide"); } /** * 头像悬浮框插件 */ (function($){ $.fn.avatar_hover = function(options){ options = $.extend({ }, options); return this.each(function(){ var userId = $(this).attr("data_userId"); var iconUrl = $(this).attr("data_iconUrl"); $(this).mouseover(function(){ avatarOnMouseOver(this, userId, iconUrl); }) $(this).mouseout(function(){ avatarOnMouseOut(this, userId, iconUrl); }) }); }; })(jQuery)
<div id="avatar_img" class="z haoyu" data_userId="${topicInfo.topicUserVo.userId }" data_iconUrl="${topicInfo.topicUserVo.iconUrl}" > <a href="#"><img class="gb_v42" src="${topicInfo.topicUserVo.iconUrl }"></a> </div>
头像布局, 函数中利用avatar_img这个id全局初始化
<script src="${rc.contextPath}/common/static/lib/avatar_hover/js/avatar_hover_window.js" type="text/javascript"></script> <#-- 话题头像悬浮框 库 END --> <div class="b-card hide" id="iuyt"> <div class="bc-bgimg"> <div class="bc-icon"><img id="avatarIconUrl" class="gb_v72" src="" /></div> <div class="bc-name" id="avatarName"></div> <div class="bc-post" id="avatarOrganizationName"></div> <div class="bc-oname" id="avatarCompanyName"></div> <ul class="bc-more"> <li id="">手机:保密</li> <li id="avatarPhone">电话:</li> <li id="avatarEmail">邮箱:</li> </ul> </div> </div><!--limia--> <script type="text/javascript" > $(function(){ $("#avatar_img").avatar_hover({ }); }) </script>