【问题标题】:Add class to div if url for image in this div is the same as current page如果此 div 中图像的 url 与当前页面相同,则将类添加到 div
【发布时间】:2017-10-06 10:45:39
【问题描述】:

我有一个看起来像这样的项目列表 (<li>):

<div class="image_frame">
     <div>
          <div>
               <a href="link 1"><img /></a>
          </div>
     </div>
</div>

如果当前页面 URL 与项目 URL 相同,我想使用 image_frame 向 div 添加其他类(如果项目链接与我的页面相同,我只想突出显示这个特定的 div访问)。

我找到了非常接近的解决方案,但是它将类添加到当前链接,而不是父 div,而是上面 3 个级别。

JavaScript add class depending on current URL

有什么建议吗?谢谢!

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    "use strict";
    
    let div = document.querySelector('.image_frame');
    let ref = 'http://domains.com/link-1/'; // delete this, it's just for test
    // let ref = window.location.href; // insert this
    let url = div.querySelector('img').parentNode.href;
    
    if (url === ref) {
        div.className += ' new_class';
        console.log('DIV class was changed to: ' + div.className);
    }
    <div class="image_frame">
        <div>
            <div>
                <a href="http://domains.com/link-1/"><img /></a>
            </div>
        </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多