DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript實現鼠標右鍵特色菜單
Javascript實現鼠標右鍵特色菜單
編輯:關於JavaScript     

在Web端,通常是不需要右鍵菜單,各個浏覽器也有自己的右鍵菜單。但是對於一些特殊的網頁,是需要右鍵菜單來增加用戶體驗的,比如百度音樂,QQ郵箱,相信大家都在Web端使用過右鍵菜單了,現在來分享一下如何實現,比較簡單。

運行代碼:

window.onload = function() {
      document.oncontextmenu = block;
      document.body.onmouseup = function(event) {
        if (!event) event = window.event;
        if (event.button == 2) {
          var x = event.pageX || event.clientX;
          var y = event.pageY || event.clientY;
          document.getElementById("contextMenu").style.left = x  "px";
          document.getElementById("contextMenu").style.top = y  "px";
          document.getElementById("contextMenu").style.display = "block";
        }
      }
      //阻止事件冒泡
      document.getElementById("contextMenu").onclick = function(event) {
        event.stopPropagation();
      }
      //點擊其他地方隱藏
      document.onclick = function() {
        document.getElementById("contextMenu").style.display = "none";
      }
      for (var i = 0; i < getElementsByClassName("contextMenuItem").length; i ) {
 
        getElementsByClassName("contextMenuItem")[i].onclick = function(event) {
          event = event ? event : window.event
          var target = event.srcElement ? event.srcElement : event.targe;
          document.getElementById("contextMenu").style.display = "none";
          //alert("您點擊了: "  target.innerHTML);
           
        }
      }
 
    }
     
    function block(event) {
      if (window.event) {
        event = window.event;
        event.returnValue = false;
      } else event.preventDefault();
    }
    //兼容IE不支持getElementsByClassName
    function getElementsByClassName(className, root, tagName) {
      if (root) {
        root = typeof root == "string" ? document.getElementById(root) : root;
      } else {
        root = document.body;
      }
      tagName = tagName || "*";
      if (document.getElementsByClassName) { 
        return root.getElementsByClassName(className);
      } else {
        var tag = root.getElementsByTagName(tagName); 
        var tagAll = [];
        for (var i = 0; i < tag.length; i ) {
          for (var j = 0, n = tag[i].className.split(' '); j < n.length; j ) {
            if (n[j] == className) {
              tagAll.push(tag[i]);
              break;
            }
          }
        }
        return tagAll;
      }
    }

效果圖:

以上就是本文的全部內容,希望大家可以喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved