我编写了一个小的jQuery插件,在触发click事件的位置打开一个弹出窗口,如果弹出窗口离开窗口以避免滚动,则将弹出窗口与窗口对齐。
(function($){
$.fn.showPopupAtEvt = function(options){
var defaults = $.extend({
/**Right popup right to the event position**/
rightAlign:false
},options);
// alert(defaults.rightAlign);
/***
m - CSS Compatibility mode
l - left offset of the window
t - top offset of the window
w - width of the window
h - height of the window
pW - Popup width
pH - Popup height
tW - Total Width(Event left offset + Popup Width)
tH - Total Height(Event top offset + Popup Height)
***/
var m,l,t,w,h,pW,pH,tW,tH;
/*****Getting popup height and width ********/
pW = this.outerWidth() || 0;
pH = this.outerHeight() || 0;
m = document.compatMode == 'CSS1Compat';
l = window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft);
t = window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop);
w = window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth);
h = window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight);
w += l;
h += t;
/*****Getting event positions ****/
mouseX = event.clientX?event.clientX:event.pageX;
mouseY = event.clientY?event.clientY:event.pageY;
/****** with scrolling positions*****/
mouseX += l;
mouseY += t;
tW = mouseX + pW;
tH = mouseY + pH;
if(tH>h){
diff = tH - h+17;
mouseY -= diff;
}
if(!defaults.rightAlign){
if(tW>w){
diff = tW - w +17;
mouseX -= diff;
}
}
else{
mouseX = mouseX - pW;
}
mouseX = mouseX<0?0:mouseX;
mouseY = mouseY<0?0:mouseY;
this.show().css({left:mouseX,top:mouseY});
/** this.show().position({left:mouseX,top:mouseY});
console.log(this.parent().css('position'));**/
};
}(jQuery));
除了一种情况外,它适用于所有地方。
如果源元素的父position is relative.
无法正常工作
我知道,由于position:relative
样式,目标弹出窗口未正确对齐,但我不知道如何解决问题。
有人能帮帮我吗.....
这是jsfiddle