How to bind click event to object tag?

前端 未结 2 2060
Happy的楠姐
Happy的楠姐 2020-11-30 12:39

I have this code


and jquery



        
相关标签:
2条回答
  • 2020-11-30 13:15

    The easiest way to accomplish this goal is to wrap the object tag in a div, bind the click listener to the div, and add pointer-events: none to the object tag's styles.

    Sample fiddle:

    .clickable {
      background: red;
      width: 100px;
      height: 100px;
      border-radius: 100px;
      overflow: hidden;
    }
    
    object {
      width: 100%;
      pointer-events: none;
    }
    <div class='clickable' onclick='alert("WOW")'>
      <object type='image/svg+xml' data='https://douglasduhaime.com/assets/images/icons/home.svg' />
    </div>

    0 讨论(0)
  • 2020-11-30 13:24

    1. Issue: Event handling

    Concerning the jQuery part, try to use event delegation.

    From the docs:

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

    $(document).on('click', '.icon-logo', function(event) {
        document.write('Event type: ' + event.type);
        document.write('<br>CSS-Class: ');
        document.write($(this).attr('class'));
    });
    // As said in the docs, you can attach multiple events to multiple selectors. 
    // A typical example of use may be:
    // $(document).on('change blur', '.icon-logo .some-other-class', function() {...}
     
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <object data="images/logo.svg" type="image/svg+xml" class="icon-logo" style="cursor: pointer;">Click me!</object>


    Edit after @Kaiido's comment:

    2. Issue: The <object> element can't be clicked.

    One possibility could be to not use an <object> at all but an <img> tag instead as suggested in this SO answer: make an html svg object also a clickable link.


    2. Issue: Empty HTML-tag

    This kind of tag <object> needs some content to show up on the page.

    Your tag:

    <object data="images/logo.svg" type="image/svg+xml" class="icon-logo"></object>

    is not having any inner HTML-Content, so you won't be able to click it.

    0 讨论(0)
提交回复
热议问题