我编写了一个小型 jQuery 插件,用于在触发单击事件的位置打开一个弹出窗口,并在弹出窗口超出窗口时将其与窗口中对齐以避免滚动。
(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