Making an svg image object clickable with onclick, avoiding absolute positioning

前端 未结 13 1177
轻奢々
轻奢々 2020-12-02 13:54

I have tried to change the images on my site from img to svg, changing img tags to embed and object tags. Bu

13条回答
  •  心在旅途
    2020-12-02 14:47

    When embedding same-origin SVGs using , you can access the internal contents using objectElement.contentDocument.rootElement. From there, you can easily attach event handlers (e.g. via onclick, addEventListener(), etc.)

    For example:

    var object = /* get DOM node for  */;
    var svg = object.contentDocument.rootElement;
    svg.addEventListener('click', function() {
      console.log('hooray!');
    });
    
    
    

    Note that this is not possible for cross-origin elements unless you also control the origin server and can set CORS headers there. For cross-origin cases without CORS headers, access to contentDocument is blocked.

    提交回复
    热议问题