【问题标题】:Link with image on popup don't work in chrome extention与弹出窗口中的图像链接在 chrome 扩展中不起作用
【发布时间】:2014-01-08 16:50:50
【问题描述】:

与弹出窗口中的图像链接不起作用。 比如这样的代码。

<a href="https://test.com/"><img src="test.png"></a>

我通过 Javascript 上的“onclick”来处理这个问题。

有没有正常工作链接图片的好方法?

【问题讨论】:

    标签: javascript html google-chrome google-chrome-extension


    【解决方案1】:

    既然你是 not allowed 拥有内联事件处理程序,你可以添加一个外部 JS 文件(例如 popup.js)并为click 事件注册监听器(使用addEventListener()) .例如:

    popup.html:

    <!DOCTYPE html>
    <html>
    <head>
        ...
        <script type="text/javascript" src="popup.js"></script>
    </head>
    <body>
        ...
        <a href="https://test.com/"><img src="test.png"></a>
    </body>
    </html>
    

    popup.js:

    document.addEventListener('DOMContentLoaded', function() {
    
        /* Get all images that are direct descendants of anchor elements */
        var imgsInAs = document.querySelectorAll('a > img');
    
        /* For each such img element... */
        [].slice.call(imgsInAs).forEach(function(img) {
    
            /* ...register a listener for the 'click' event that... */
            img.addEventListener('click', function(evt) {
    
                /* ...simulates a 'click' on its parent-node 
                 * (i.e. the anchor element) */
                evt.preventDefault();
                img.parentNode.click();
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2011-03-13
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 2016-07-18
      • 2017-12-29
      • 2012-10-09
      相关资源
      最近更新 更多