简体   繁体   English

如何从多个元素中删除一个类,然后仅将一个类添加到 JavaScript 中选择的一个类?

[英]How to remove a class from multiple elements then add a class only to the one selected in JavaScript?

I have written a small JavaScript program which adds a right click context menu on multiple elements (p tags in this example).我编写了一个小型 JavaScript 程序,它在多个元素(本例中为 p 标签)上添加了一个右键单击上下文菜单。 When you right click each text, the context menu appears correctly and disappears when left clicking outside the menu.当您右键单击每个文本时,上下文菜单会正确显示并在菜单外单击鼠标左键时消失。

However when you right click one element and immediately right click the other element both context menus appear.但是,当您右键单击一个元素并立即右键单击另一个元素时,两个上下文菜单都会出现。 I want to be able only show one menu at a time.我希望一次只能显示一个菜单。 How do I clear all '.show' classes first, then add the class only to the one that was right clicked?如何首先清除所有“.show”类,然后仅将类添加到右键单击的类? I tried adding a if statement into the 'show' function but the behaviour is still the same.我尝试在 'show' 函数中添加一个 if 语句,但行为仍然相同。 See fiddle below.见下面的小提琴。 Thanks谢谢

https://jsfiddle.net/Lwdtoc12 https://jsfiddle.net/Lwdtoc12

The js: js:

document.addEventListener('DOMContentLoaded', function () {

    let rightClickElement = document.querySelectorAll('.right-clickable-element');

    rightClickElement.forEach(function (element) {
        let menu = element.parentElement.querySelector('.right-clickable-menu');
        element.addEventListener('contextmenu', function (e) {
            // hide default right click menu
            e.preventDefault();
            // show custom menu
            showMenu(e, menu);
            // hide custom menu
            hideMenu(menu);
        });
    });

    function showMenu(e, menu) {
        if (menu.classList.contains('show')) {
            menu.classList.remove('show');
        } else {
            menu.classList.add('show');
            menu.style.top = e.clientY - 10 + 'px';
            menu.style.left = e.clientX - 10 + 'px';
        }
        //console.log(menu.classList.contains(''));

    }

    function hideMenu(menu) {
        document.addEventListener('click', function (e) {
            if (e.target !== menu && !menu.contains(e.target)) {
                menu.classList.remove('show');
            }
        });
    }

});

In showMenu method, get all menu items and remove .show class.showMenu方法中,获取所有菜单项并删除.show类。 Then toggle the class for the current selected menu.然后切换当前选定菜单的类。

function showMenu(e, menu) {
  let allMenu = document.querySelectorAll('.right-clickable-menu');

  allMenu.forEach(function(el) {
    el.classList.remove('show');
  });

  menu.classList.toggle('show');
  menu.style.top = e.clientY - 10 + 'px';
  menu.style.left = e.clientX - 10 + 'px';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM