【问题标题】:Set opacity with js or close modal window用js设置不透明度或关闭模态窗口
【发布时间】:2015-10-07 07:04:14
【问题描述】:

我想“关闭”一个模态窗口。这是一个wordpress模板,而且很丑…… 我有一个 div:

<div class="modal">
    <section style="position:relative;z-index:10;">
        <div style="margin-bottom: -50px; margin-right: 50px; text-align: right;">
            <img src="./wp-content/img.png" alt="Close">
        </div>
        <p><img src="./wp-content/img2.png" alt="test"></p>
    </section>
</div>

而当点击带有alt="Close"的img时,我想关闭或将所有div.modal的不透明度设置为0。用JS可以吗?

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    jQuery

    $('img[alt*=Close]').click(function() {
        $('.modal').hide();
    });
    

    JS

    var img = document.querySelector('img[alt*=Close]'),
           modal = document.querySelector('.modal');
    img.addEventListener('click', function() {
        modal.style.display = 'none';
    });
    

    【讨论】:

    【解决方案2】:

    当点击带有alt="Close"的img时,我想关闭或设置所有div.modal中的opacity为0。

    绝对!

    首先我想提一下,有一些属性选择器现在在 css3 中正式可用,因此可以用作 jQuery 选择器,例如:

    $('body').on('click', 'img[alt="Close"]', function(e){
        $(this).closest('.modal').fadeOut(); // to fade out the entire div.
        // $(this).closest('.modal').hide(); // hide will hide the modal
    });
    

    如果您的模态是动态创建的,那么您必须遵循事件委托技术,其语法如下:

    $(staticParent).on(event, selector, callback);
    

    【讨论】:

    • 一个小问题... 创建模态窗口时,网站 URL 变为:url.com/#idModal。如果我隐藏它,即使使用window.location,URL 也会保持#idModal。我无法打开其他模式窗口。隐藏模态后有什么方法可以恢复基本网址?
    【解决方案3】:

    是的!只需设置 css 属性 opacity

    $(".modal").css({ opacity: 0.5 });

    【讨论】:

    • 谢谢!在 img 上的点击事件上?
    • 是的!如果这就是你想要的。
    【解决方案4】:

    您可以通过以下方式监听 img div 上的点击事件:

    document.querySelector("img[alt=Close]").addEventListener("click", yourHandler);
    

    然而,使用其alt 属性访问图像看起来是个糟糕的主意。 alt 是为用户显示信息提示和可访问性消息,而不是识别 DOM 元素。 如果你能给这个图像一个 id 或一个类,那就更好了:

    document.getElementById("yourImgId").addEventListener("click", yourHandler);
    

    然后:

    var modal = document.querySelector(".modal");
    
    function yourHandler(){
       modal.style.opacity = 0;
    }
    

    function yourHandler(){
       modal.style.display = "none";
    }
    

    最后一种解决方案是在样式表中定义样式属性,例如:

    .modal.disabled {
        display: none;
    }
    

    然后将该类添加到modal 以禁用它。

    function yourHandler(){
        modal.classList.add("disabled");
    }
    

    最后一种解决方案更灵活,更易于维护,因为它将逻辑与样式分开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-24
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多