Positioning of Context menu
I have developed a right click context menu in javascript for table .The position of context menu is at the down of cursor for every row of table.The final row of table is at end of the page,Now on right clicking the row the context menu is coming down but it should be shown up the cursor.Any help please
function ContextShow(event) {
event = event || window.event;
var m = getMousePosition(event);
var s = getScrollPosition(event);
var client_height = document.body.clientHeight;
var display_context = document.getElementById('context_menu');
if(replaceContext){
display_context.style.display = "block";
display_conte开发者_运维技巧xt.style.left = m.x + s.x + "px";
display_context.style.top = m.y + s.y + "px";
replaceContext = false;
}}
function getMousePosition (e){
e = e || window.event;
var position = {
'x' : e.clientX,
'y' : e.clientY
}
return position;}
function getScrollPosition(){
var x = 0;
var y = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
x = window.pageXOffset;
y = window.pageYOffset;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
x = document.body.scrollLeft;
y = document.body.scrollTop;
}
var position = {
'x' : x,
'y' : y
}
return position;
}
Here, the contextShow will display the context menu of right click based on the mouse position using getMousePosition(event); and getScrollPosition(event);
I use the following function to set context menu position, and it works for me.
function setContextMenuPostion(event, contextMenu) {
var mousePosition = {};
var menuPostion = {};
var menuDimension = {};
menuDimension.x = contextMenu.outerWidth();
menuDimension.y = contextMenu.outerHeight();
mousePosition.x = event.pageX;
mousePosition.y = event.pageY;
if (mousePosition.x + menuDimension.x > $(window).width() + $(window).scrollLeft()) {
menuPostion.x = mousePosition.x - menuDimension.x;
} else {
menuPostion.x = mousePosition.x;
}
if (mousePosition.y + menuDimension.y > $(window).height() + $(window).scrollTop()) {
menuPostion.y = mousePosition.y - menuDimension.y;
} else {
menuPostion.y = mousePosition.y;
}
return menuPostion;
}
When displaying the context menu you should check if the mouse cursor is in the bottom half or the top half of the screen.Then if it is the bottom half you should display it at top of the cursor and vice versa.This can be applied for the right and left half of the screen too so then your menu will appear depending in which quarter of the screen your cursor is.if you do this, you are sure that your menu is always visible no mater where you cursor is.
Ex: if mouse x coordinates > screen height/2 than display menu on top of the cursor...
精彩评论