鼠标右键自定义菜单

效果图

代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <title>鼠标右键自定义菜单</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="author" content="">
    <style type="text/css">
    #contextmenu {
      position: absolute;
      width: 80px;
      height: 34px;
      background-color: #FFF;
      border: 1px solid #CED4E0;
      left: 0;
      top: 100px;
      display: none;
    }
    #contextmenu a {
      margin-top: 2px;
      display: block;
      width: 100%;
      height: 30px;
      font-size: 12px;
      line-height: 30px;
      text-align: center;
      text-decoration: none;
      color: #7A96CC;
    }
    #contextmenu a:hover {
      background-color: #7A96CC;
      color: #FFF;
    }
    #itemList {
      position: relative;
      width: 300px;
      height: 500px;
      overflow: auto;
      margin: 0;
      border: 1px solid #DDD;
      background: #F5F5F5;
    }
    #itemList .item {
      height: 50px;
      line-height: 50px;
      border-bottom: 1px solid #DDD;
      text-indent: 10px;
    }
    #itemList .item:hover {
      background-color: #EEE;
    }
    </style>

</head>
<body>
<div id="itemList">
  <div class="item">右键菜单1</div>
  <div class="item">右键菜单2</div>
  <div class="item">右键菜单3</div>
  <div class="item">右键菜单4</div>
  <div class="item">右键菜单5</div>
<div>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script>
$(function(){
  $('body').append('<div id="contextmenu"><a href="javascript:">删除</a></div>')
    $(document).delegate('.item','contextmenu',function(e){
      var $this = $(this),
        dataId = $this.attr('data-id'),
        $contextmenu = $('#contextmenu');
      $contextmenu.find('a').attr('data-id',dataId);
      $this.addClass('active');
      //加上window.scrollY是考虑页面有滚动过的情况
      $contextmenu.css({'left':e.clientX,'top':e.clientY+window.scrollY}).show();
      e.preventDefault();
    })
    $(document).delegate('#contextmenu a','click',function(){
      var $this = $(this);
      $('.item.active').remove();
    })
    $('body').on('click',function(){
      $('#contextmenu').hide();
    })
})
</script>
</body>
</html>

 

posted @ 2015-10-23 15:28  zhouzone  Views(405)  Comments(0Edit  收藏  举报