简体   繁体   中英

How to append a class if element contains certain CSS property

I want to add 'onclick' functionality to certain elements. These elements are perfectly targeted with this CSS, setting pointer-events to 'auto':

.custom-collections .o_slideshow .end-group {
    pointer-events: auto;
}

.custom-collections > .o_slideshow:first-child,
.custom-collections > .o_slideshow .o_slide[data-id="home_slide"],
.custom-collections > .o_slideshow:last-child {
    pointer-events: auto;
}

My javascript currently enables the elements to be dragged (on drag) and previewed (on long touch). Ultimately, I need it only to be previewed .

In the javascript, I include this, to disable drag functionality if 'defaultSlide' is one of the classes:

            if (event.target.classList.contains('defaultSlide')) {
                // If the slide contains 'defaultSlide', it shouldn't be draggable.
                return;
            }

How should I append the class defaultSlide to the elements? Alternatively, what else could I do, instead of an if class method, to have my drag-script return immediately?

Normally, I would add the class 'defaultSlide' to these elements in javascript when the elements are first created, but that requires a lot of code in my context of bad legacy code

If that CSS perfectly targets the elements, you have at least two options:

  1. Element#matches checks to see if the element you call it on matches the CSS selector you provide. So you could use Element#matches instead of your class check when you get the event, to see if the element matches those selectors:

     var selectors = '.custom-collections .o_slideshow .end-group, ' + '.custom-collections > .o_slideshow:first-child, ' + '.custom-collections > .o_slideshow .o_slide[data-id="home_slide"], ' + '.custom-collections > .o_slideshow:last-child'; if (event.target.matches(selectors)) { // return; } 
  2. document.querySelectorAll returns a collection of elements that match the CSS selector you provide. So on page load, you could use querySelectorAll to get all elements matching those selectors and add the class to them:

     var selectors = '.custom-collections .o_slideshow .end-group, ' + '.custom-collections > .o_slideshow:first-child, ' + '.custom-collections > .o_slideshow .o_slide[data-id="home_slide"], ' + '.custom-collections > .o_slideshow:last-child'; document.querySelectorAll(selectors).forEach(function(e) { e.classList.add("defaultSlide"); }); 

    ...and then use your existing code that checks for the class when you get the event.


Side note: The object returned by querySelectorAll only recently got the forEach method used above; see this answer for details and workaround for slightly out-of-date browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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