javascript 在 jQuery 的 contextMenu 插件中定义图标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26800350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:30:52  来源:igfitidea点击:

Defining icons in the contextMenu plugin of jQuery

javascriptjquerywebcontextmenu

提问by Mussé Redi

So far, I was able to create a contextMenu that binds to a right mouse cilck by including the javascript in a html file:

到目前为止,我能够通过在 html 文件中包含 javascript 来创建一个绑定到鼠标右键的 contextMenu:

var Feature = {
    register_contextMenu: function() {
        $.contextMenu({
            selector: '*',
            items: {
                "item_one": { name: "Item_one", icon: "./path1" },
                "item_two": { name: "item_two", icon: "./path2" }
            }
        });
    }
};

$(document).ready(Feature.register_contextMenu);

How would one go about displaying icons alongside the options?

如何在选项旁边显示图标?

The documentation of the plugin(http://medialize.github.io/jQuery-contextMenu/) mentions that one has to define icons in CSS with certain selectors.

该插件的文档(http://medialize.github.io/jQuery-contextMenu/)提到必须使用某些选择器在 CSS 中定义图标。

How does one use CSS with contextMenu in this case?

在这种情况下,如何将 CSS 与 contextMenu 一起使用?

回答by Mr. Polywhirl

Did you check out the source codefor the demo on Github?

您是否在 Github 上查看了演示的源代码

Looks like you just add a CSS class:

看起来您只是添加了一个 CSS 类:

.context-menu-item.icon-<NAME-OF-ICON> {
    background-image: url(images/<NAME-OF-ICON>.png);
}

The docs also state:

文档还指出:

(string) icon
Specifies the icon class to set for the item.

Icons must be defined in CSS with selectors like .context-menu-item.icon-edit, where edit is the icon class.

( string) icon
指定要为项目设置的图标类。

图标必须在 CSS 中使用选择器定义,例如 .context-menu-item.icon-edit,其中 edit 是图标类。

The create() function is responsible for attaching the class for the icons to the items. This code appears on line 1077of the current source code.

create() 函数负责将图标的类附加到项目。此代码出现在当前源代码的第 1077 行

// add icons
if (item.icon) {
     $t.addClass("icon icon-" + item.icon);
}

From the demo:

从演示:

/* icons
    #protip:
    In case you want to use sprites for icons (which I would suggest you do) have a look at
    http://css-tricks.com/13224-pseudo-spriting/ to get an idea of how to implement 
    .context-menu-item.icon:before {}
 */
.context-menu-item.icon { min-height: 18px; background-repeat: no-repeat; background-position: 4px 2px; }
.context-menu-item.icon-edit { background-image: url(images/page_white_edit.png); }
.context-menu-item.icon-cut { background-image: url(images/cut.png); }
.context-menu-item.icon-copy { background-image: url(images/page_white_copy.png); }
.context-menu-item.icon-paste { background-image: url(images/page_white_paste.png); }
.context-menu-item.icon-delete { background-image: url(images/page_white_delete.png); }
.context-menu-item.icon-add { background-image: url(images/page_white_add.png); }
.context-menu-item.icon-quit { background-image: url(images/door.png); }


Demo

演示

I removed the "edit", "delete", and "add" menu-items from the exampleand added a "Share on Google+", "Share on Facebook", and "Save" option to the menu.

我从示例中删除了“编辑”、“删除”和“添加”菜单项,并在菜单中添加了“在 Google+ 上共享”、“在 Facebook 上共享”和“保存”选项。

Just press "Run code snippet" below to see it in action.

只需按下面的“运行代码片段”即可查看它的运行情况。

$(function(){
  $.contextMenu({
    selector: '.context-menu-one', 
    callback: function(key, options) {
      var m = "clicked: " + key;
      window.console && console.log(m) || alert(m); 
    },
    items: {
      "cut"      : { name: "Cut",               icon: "cut" },
      "copy"     : { name: "Copy",              icon: "copy" },
      "paste"    : { name: "Paste",             icon: "paste" },
      "sep1"     : "---------",
      "google"   : { name: "Share on Google+",  icon: "google-plus" },
      "facebook" : { name: "Share on Facebook", icon: "facebook" },
      "sep2"     : "---------",
      "save"     : { name: "Save",              icon: "save" },
      "quit"     : { name: "Quit",              icon: "quit" }
    }
  });

  $('.context-menu-one').on('click', function(e){
    console.log('clicked', this);
  })
});
.context-menu-icon {
  min-height: 18px; background-repeat: no-repeat; background-position: 4px 2px;
}

.context-menu-icon-save {
  /* Source: http://www.famfamfam.com/lab/icons/silk/icons/disk.png */
  background-image: url("http://i.imgur.com/4LyeGi1.png");
}

.context-menu-icon-facebook {
  /* Source: http://icons.iconarchive.com/icons/yootheme/social-bookmark/16/social-facebook-box-blue-icon.png */
  background-image: url("http://i.imgur.com/EVcCwyZ.png");
}

.context-menu-icon-google-plus {
  /* Source: https://cdn1.iconfinder.com/data/icons/professional-toolbar-icons-2/16/Google_plus_google.png */
  background-image: url("http://i.imgur.com/Zg0UFmq.png");
}
<link href="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.js"></script>

<div class="context-menu-one box menu-1">
  <strong>Right-Click ME!</strong>
</div>



Update

更新

I suggest that you use a font icon library such as FontAwesome. This is the easiest solution.

我建议您使用字体图标库,例如 FontAwesome。这是最简单的解决方案。

$(function(){
  $.contextMenu({
    selector: '.context-menu-one', 
    callback: function(key, options) {
      var msg = "clicked: " + key;
      window.console && console.log(msg) || alert(msg); 
    },
    items: {
      "cut"      : { name: "Cut",               icon: "cut" },
      "copy"     : { name: "Copy",              icon: "copy" },
      "paste"    : { name: "Paste",             icon: "paste" },
      "sep1"     : "---------",
      "google"   : { name: "Share on Google+",  icon: "google-plus" },
      "facebook" : { name: "Share on Facebook", icon: "facebook" },
      "sep2"     : "---------",
      "save"     : { name: "Save",              icon: "save" },
      "quit"     : { name: "Quit",              icon: "quit" }
    }
  });

  $('.context-menu-one').on('click', function(e){
    console.log('clicked', this);
  })
});
.context-menu-icon.context-menu-icon-save:before,
.context-menu-icon.context-menu-icon-facebook:before,
.context-menu-icon.context-menu-icon-google-plus:before {
  font-family: FontAwesome !important;
}

.context-menu-icon.context-menu-icon-save:before {
  content: "\f0c7"; /* fa-floppy-o */
}

.context-menu-icon.context-menu-icon-facebook:before {
  content: "\f230"; /* fa-facebook-official */
}

.context-menu-icon.context-menu-icon-google-plus:before {
  content: "\f0d4"; /* fa-google-plus-square */
}
<link href="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.js"></script>

<div class="context-menu-one box menu-1">
  <strong>Right-Click ME!</strong>
</div>

It looks like FontAwesome is supported with this plugin, so you do not need to customize any CSS.

看起来这个插件支持 FontAwesome,所以你不需要自定义任何 CSS。

$(function(){
  $.contextMenu({
    selector: '.context-menu-one', 
    callback: function(key, options) {
      var msg = "clicked: " + key;
      window.console && console.log(msg) || alert(msg); 
    },
    items: {
      "cut"      : { name: "Cut",               icon: "cut" },
      "copy"     : { name: "Copy",              icon: "copy" },
      "paste"    : { name: "Paste",             icon: "paste" },
      "sep1"     : "---------",
      "google"   : { name: "Share on Google+",  icon: "fa-google-plus-square" },
      "facebook" : { name: "Share on Facebook", icon: "fa-facebook-official" },
      "sep2"     : "---------",
      "save"     : { name: "Save",              icon: "fa-floppy-o" },
      "quit"     : { name: "Quit",              icon: "quit" }
    }
  });

  $('.context-menu-one').on('click', function(e){
    console.log('clicked', this);
  })
});
<link href="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.rawgit.com/swisnl/jQuery-contextMenu/master/dist/jquery.contextMenu.js"></script>

<div class="context-menu-one box menu-1">
  <strong>Right-Click ME!</strong>
</div>

回答by wobuntu

It has been a while since you asked for help... Anyway, try to adapt the following code (It just sums up Mr. Polywhirl's answer into a single file for easier understanding). As you can see, the menu's first three items contain custom icons, while the last one uses one of the built-in .svg pictures.

自从您寻求帮助以来已经有一段时间了...无论如何,请尝试修改以下代码(它只是将 Polywhirl 先生的答案汇总到一个文件中以便于理解)。如您所见,菜单的前三项包含自定义图标,而最后一项使用内置 .svg 图片之一。

If you use external resources as I do in this example, make sure that you are able to access them (Open Chrome's Dev-Tools by pressing Strg + I and watch out for error messages in the console) and as always make sure that you are allowed to use them.

如果您像我在本示例中那样使用外部资源,请确保您能够访问它们(按 Strg + I 打开 Chrome 的开发工具并注意控制台中的错误消息)并始终确保您是允许使用它们。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8" />
  <!-- include the context-menu from cdnjs -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.0.1/jquery.contextMenu.min.css" />
  <style>
    .context-menu-abc {
      border: 1px solid gray;
      padding: 5px;
    }
    /* used for all items */
    
    .context-menu-item {
      min-height: 18px;
      background-repeat: no-repeat;
      background-position: 4px 4px;
    }
    /* all custom icons */
    
    .context-menu-item.context-menu-icon-firstOpt {
      background-image: url("https://cdn4.iconfinder.com/data/icons/6x16-free-application-icons/16/Boss.png");
    }
    
    .context-menu-item.context-menu-icon-secondOpt {
      background-image: url("https://cdn4.iconfinder.com/data/icons/6x16-free-application-icons/16/Save.png");
    }
    
    .context-menu-item.context-menu-icon-thirdOpt {
      background-image: url("https://cdn4.iconfinder.com/data/icons/6x16-free-application-icons/16/OK.png");
    }
  </style>
</head>

<body>
  <div><span class="context-menu-abc">right-click this box</span></div>

  <!-- try to include scripts at the end so the DOM can be created faster -->
  <script src="js/jquery-2.1.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.0.1/jquery.contextMenu.min.js"></script>

  <script>
    $(function() {
      "use strict";
      $.contextMenu({
        selector: '.context-menu-abc',
        callback: function(key, options) {
          if (key === 'firstOpt') {
            // specific code for your first option
          } else if (key === 'secondOpt') {
            // specific code for your second option
          } else if (key === 'thirdOpt') {
            // specific code for your third option
          }
        },
        items: {
          'firstOpt': {
            name: "First option",
            icon: "firstOpt"
          },
          'secondOpt': {
            name: "Second choice",
            icon: "secondOpt"
          },
          'thirdOpt': {
            name: "Third option",
            icon: "thirdOpt"
          },
          'copy': {
            name: "Fourth option",
            icon: "copy"
          }
        }
      });
    });
  </script>
</body>

</html>

Hope that helped.

希望有所帮助。

回答by SunOfABee

Using the Mr PolyWhirls example above I still couldn't get it to work properly. The FontAwesome icon was not aliging properly etc. I imagine that there has been an update to the plugin somewhere along the way that has broken support for FA 4. (There were changes to FA 4 when FA 5 came out). My solution was to go back to using custom CSS...

使用上面的 Mr PolyWhirls 示例,我仍然无法使其正常工作。FontAwesome 图标未正确对齐等。我想在此过程中某个插件的更新已经破坏了对 FA 4 的支持。(FA 5 出现时对 FA 4 进行了更改)。我的解决方案是回到使用自定义 CSS ...

<style type="text/css">
    .context-menu-icon.context-menu-icon-file-alt:before {
        font-family: FontAwesome !important;
        color: #2980B9;
          font-style: normal;
          font-weight: normal;
          font-size: 16px;
          left: 0;
          line-height: 1;
          position: absolute;
          text-align: center;
          top: 50%;
          transform: translateY(-50%);
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          width: 28px;

    }
    .context-menu-icon.context-menu-icon-file-alt:before{
        content: '\f15c';
    }
</style>