contextmenu.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. class ContextMenu {
  2. constructor(player) {
  3. this.player = player;
  4. this.shown = false;
  5. Array.prototype.slice.call(this.player.template.menuItem).forEach((item, index) => {
  6. if (this.player.options.contextmenu[index].click) {
  7. item.addEventListener('click', () => {
  8. this.player.options.contextmenu[index].click(this.player);
  9. this.hide();
  10. });
  11. }
  12. });
  13. this.player.container.addEventListener('contextmenu', (e) => {
  14. if (this.shown) {
  15. this.hide();
  16. return;
  17. }
  18. const event = e || window.event;
  19. event.preventDefault();
  20. const clientRect = this.player.container.getBoundingClientRect();
  21. this.show(event.clientX - clientRect.left, event.clientY - clientRect.top);
  22. this.player.template.mask.addEventListener('click', () => {
  23. this.hide();
  24. });
  25. });
  26. }
  27. show(x, y) {
  28. this.player.template.menu.classList.add('dplayer-menu-show');
  29. const clientRect = this.player.container.getBoundingClientRect();
  30. if (x + this.player.template.menu.offsetWidth >= clientRect.width) {
  31. this.player.template.menu.style.right = clientRect.width - x + 'px';
  32. this.player.template.menu.style.left = 'initial';
  33. } else {
  34. this.player.template.menu.style.left = x + 'px';
  35. this.player.template.menu.style.right = 'initial';
  36. }
  37. if (y + this.player.template.menu.offsetHeight >= clientRect.height) {
  38. this.player.template.menu.style.bottom = clientRect.height - y + 'px';
  39. this.player.template.menu.style.top = 'initial';
  40. } else {
  41. this.player.template.menu.style.top = y + 'px';
  42. this.player.template.menu.style.bottom = 'initial';
  43. }
  44. this.player.template.mask.classList.add('dplayer-mask-show');
  45. this.shown = true;
  46. this.player.events.trigger('contextmenu_show');
  47. }
  48. hide() {
  49. this.player.template.mask.classList.remove('dplayer-mask-show');
  50. this.player.template.menu.classList.remove('dplayer-menu-show');
  51. this.shown = false;
  52. this.player.events.trigger('contextmenu_hide');
  53. }
  54. }
  55. export default ContextMenu;