简体   繁体   中英

Onclick event on Object HTML Tag doesn't work, workaround?

So I have an SVG imported via the <object> tag and it has a onclick="functionName(); attached to it, but it doesn't appear to work. So I tried adding the following script in the SVG:

<svg tag here etc
<defs>
        <script type="text/javascript">
            <![CDATA[
            document.addEventListener('click', test());
            ]]>
        </script>
    <linearGradient id="bbc50e5b-4734-4535-94bd-b30475bdd571" data-name="Testingspace" x1="15" y1="310" x2="320" y2="5" gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="#ccc"/>
      <stop offset="1" stop-color="#fff"/>
    </linearGradient>
  </defs>
the rest of SVG here

My HTML:

<object id="sidebartoggle" data="graphics/test.svg" type="image/svg+xml" onclick="toggleSidebar();" style="top:50%;right:1%;position:fixed;display:flex;justify-content:flex-end;width:500px;transform: translateX(99%); z-index:9999999;" >
            </object>

...but it simply doesn't work. What's the required workaround here? What should I do to accomplish my goal - bind a click event on the SVG, which executes a function from the JS file.

The onclick event won't be bound to your object, since you're actually clicking/targeting the object's inner content (svg DOM).

As a workaround you could apply a css pointer-events:none to your object element and bind your click event to an auxiliary wrapping element.

 function toggleSidebar(){ console.log('clicked'); }
 .svg-wrp{ cursor:pointer; } .svgObject{ display:inline-block; font-size:36px; width:1em; height:1em; background-color:transparent; border:1px solid red; }
 <h3>css: "pointer-events:none" – click enabled</h3> <div class="svg-wrp" onclick="toggleSidebar()" > <object class="svgObject" id="sidebartoggle01" data="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' class='cross'%3E%3Cpolygon fill='grey' points='11.649 9.882 18.262 3.267 16.495 1.5 9.881 8.114 3.267 1.5 1.5 3.267 8.114 9.883 1.5 16.497 3.267 18.264 9.881 11.65 16.495 18.264 18.262 16.497'/%3E%3C/svg%3E" type="image/svg+xml" style="pointer-events:none" ></object> </div> <h3>Original &lt;object&gt; – click event is not available</h3> <div class="svg-wrp" onclick="toggleSidebar()" > <object class="svgObject" id="sidebartoggle01" data="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' class='cross'%3E%3Cpolygon fill='grey' points='11.649 9.882 18.262 3.267 16.495 1.5 9.881 8.114 3.267 1.5 1.5 3.267 8.114 9.883 1.5 16.497 3.267 18.264 9.881 11.65 16.495 18.264 18.262 16.497'/%3E%3C/svg%3E" type="image/svg+xml" ></object> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM