我需要一个上下文菜单,我试图设置其位置关闭指针点击。它的立场是固定的。
<ul id='cmenu'>
<li class='citem' id='c-edit'>EDIT</li>
<li class='citem' id='c-public'>PUBLIC</li>
<li class='citem' id='c-later'>PUBLIC LATER</li>
</ul>
JS
$(document).on('contextmenu', '.itemp', function(e) {
e.preventDefault();
var w = $('#cmenu').width();
var h = $('#cmenu').height();
var x = e.pageX;
var y = e.pageY;
var cx = window.innerWidth/2;
var cy = window.innerHeight/2;
var topb = y-h;
if (x <= cx) {$('#cmenu').css('left', x + 10 + 'px');}
else {$('#cmenu').css('left', x-w + 'px');}
if (y <= cy) {$('#cmenu').css('top', y + 'px');}
else {$('#cmenu').css('top', topb + 'px');}
$('#cmenu').show();
});
水平位置总是好的,但垂直有时是好的 - 有时在指针下方约50 - 70 px。我看不出原因。清除缓存无济于事。
答案 0 :(得分:0)
如果您愿意,可以使用jQuery-contextMenu plugin:
$.contextMenu({
// define which elements trigger this menu
selector: ".itemp",
// define the elements of the menu
items: {
edit: {
name: "EDIT", callback: function (key, opt) {
console.log("EDIT!");
}
},
public: {
name: "PUBLIC", callback: function (key, opt) {
console.log("PUBLIC!")
}
},
public_later: {
name: "PUBLIC LATER", callback: function (key, opt) {
console.log("PUBLIC LATER!")
}
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.min.css">
<script src="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.min.js"></script>
<script src="https://rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.ui.position.min.js"></script>
<div class="itemp">This is a sample div element: rigth mouse click to open context menu</div>
<br/>
<div>Here there is no context menu</div>
&#13;