用Javascript實現Agent(實現右鍵菜單)(2)

來源:互聯網
上載者:User

用Javascript實現Agent(實現右鍵菜單)

既然是顯示右鍵菜單,那麼我們就要截獲對精靈按右鍵時的事件oncontextmenu

然後將右鍵菜單的html封裝到一個函數,一上來這個菜單層是隱藏的

function getMenuHtml()
{
 var menuHtml ="<div id=menu style=\"text-align: left;position: absolute; visibility: hidden; width: 85px; z-index: 200;padding:1px\">";
 menuHtml += "<table border=1 width=100 height=100>";
 menuHtml += "<tr>";
 menuHtml += "<td>";
 menuHtml += "Menu1";
 menuHtml += "</td>";
 menuHtml += "</tr>";
 menuHtml += "</table>";
 menuHtml += "</div>";
 return menuHtml;
}

實現右鍵菜單,我們需要精靈截獲oncontextmenu事件,需要對昨天的run函數進行一點小的修改

Agent.prototype.run=function()
{
 var agentHtml = "";
 agentHtml += "<img src="+this.imgAgent;
 agentHtml += " id=\"agent1\"";
 agentHtml += " style=\"position:absolute;left:"+this.agentLeft+";top:"+this.agentTop+";cursor:move\"";
 agentHtml += " onselectstart=\"return false\"";
 agentHtml += " onmousedown=\"mousedown(this)\"";
 agentHtml += " onmouseup=\"mouseup()\"";
 agentHtml += " onmousemove=\"mousemove()\"";
 agentHtml += " oncontextmenu=\"return showRightMenu()\"";
 agentHtml += ">";
 agentHtml += getMenuHtml();
 return document.write(agentHtml);
}

可以看出oncontextmenu調用的是showRightMenu函數,這個函數使菜單層可見,並且顯示位置隨著滑鼠的位置而顯示

註解:

scrollLeft:設定或擷取位於對象左邊界和視窗中目前可見內容的最左端之間的距離
scrollTop:設定或擷取位於對象最頂端和視窗中可見內容的最頂端之間的距離
event.clientX:滑鼠點擊的x軸位置
event.clientY:滑鼠點擊的y軸位置

/*
* 右鍵菜單 v1.0
* author: 清風
*/
function showRightMenu()
{
 menu.style.left=document.body.scrollLeft+event.clientX
 menu.style.top=document.body.scrollTop+event.clientY
 menu.style.visibility="visible";
 return false;
}

菜單現在可以顯示了,如何使其消失呢?應當是使用者點擊任意位置就可消失

document.onclick=click
function click()
{
 menu.style.visibility="hidden";
}

今天的效果如下:

                                                                                                                                                                                                             選擇自 changzheng 的 Blog

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.