使用JS为具有特定命名约定的所有图像添加特定类

时间:2018-06-17 06:26:36

标签: javascript css wordpress plugins responsive-design

首先,此主题与这些现有主题类似:

Adding a class to all the images within a <div> using javascript & vice versa

How to add a class to all images except specific ones with JS

情况:

我正在使用名为Responsify WP的响应式图像插件,您可以通过向图像添加rwp-not-responsive类来排除图像的响应。

我想忽略由于冲突而在另一个插件中使用的所有图像,并且理想情况下使用js来检查图像文件名的模式,约定,例如视网膜调用名为@ 2x的Retina图像。 JS。

我希望它能够成为一种香草和光,尽可能普遍。

1 个答案:

答案 0 :(得分:0)

您应该可以使用document.querySelectorAll()定位您不希望受影响的任何图片,然后使用element.classList.add

添加rwp-not-responsive课程

例如,我将为所有图片(下面的第一个JavaScript块)添加unwanted-border类,假装这是您的响应式图片插件。

然后,在第二个JavaScript块中,我将rwp-not-responsive类添加到以下所有图像中:

  1. class="people"
  2. attr="some-attr"
  3. 在其中包含src的{​​{1}}。
  4. 您可以使用blur中所需的任何复杂选择器,例如CSS Contains attribute selectorquerySelectorAll应该在src网址中抓取[attribute*="@2x"]的任何图片。

    @2x
    // Your Responsive Script, affects all images
    images = document.querySelectorAll('img');
    for( i = 0, n = images.length; i < n; ++ i ){
      images[i].classList.add('unwanted-border');
    }
    
    // Code to add rwp-not-responsive class
    skipImages = document.querySelectorAll('.people, [attr="some-attr"], [src*="blur"]');
    for( i = 0, n = skipImages.length; i < n; ++ i ){
      skipImages[i].classList.add('rwp-not-responsive');
    }
    img.unwanted-border:not(.rwp-not-responsive) {
      border: 10px solid #fff;
      border-radius: 3px;
      box-shadow: 0 10px 20px -8px #000;
    }

相关问题