js簡単なカスタム右クリックメニューを実現します.
4790 ワード
var RightMenu = function(){
this.rightMenu = null;
this.rightMenuList = [];
this.itemIndex = 0;
}
RightMenu.prototype = {
init:function(){
this._preventDefaultRightMenu(); //
this._createRightMenu(); //
this._rightClickEvent(); //
},
_preventDefaultRightMenu:function(){
document.addEventListener('contextmenu',function(event){
event.preventDefault();
},false)
},
_createRightMenu:function(){
this.rightMenu = document.createElement('ul');
this.rightMenu.id = 'rightMenu';
document.body.appendChild(this.rightMenu);
},
_rightClickEvent:function(){
// document
document.addEventListener('contextmenu',function(event){
var menu = document.getElementById('rightMenu');
menu.style.left = event.clientX + 'px';
menu.style.top = event.clientY + 'px';
menu.style.display = 'block';
},false)
},
_createRightMenuItem:function(item,callback){
var li = document.createElement('li');
li.id = 'rightMenuItem_' + this.itemIndex;
li.innerHTML = item;
this.rightMenu.appendChild(li);
li.addEventListener('click',callback,false);
this.itemIndex++;
},
addRightMenuItem:function(itemText,callback){ // ( , )
this.rightMenuList.push(itemText);
this._createRightMenuItem(itemText,callback);
}
}
//
var rightMenu = new RightMenu();
rightMenu.init();
//
rightMenu.addRightMenuItem(' ',function(event){
alert(' ')
});
rightMenu.addRightMenuItem(' ',function(event){
alert(' ')
});