Detect if I'm clicking an element within an element

前端 未结 2 1955
-上瘾入骨i
-上瘾入骨i 2020-12-19 07:16

I have an element (let\'s say div with id \"Test\") with a set height and width. Randomly placed within this element are other (smaller) elements (let\'s say id\'s \"inner1\

相关标签:
2条回答
  • 2020-12-19 07:50

    Add an onClick handler to your Test div and use event bubbling to trap clicks on the inner elements. You can extract the clicked element from the event object.

    document.getElementById("Test").onclick = function(e) {
        e = e || event
    var target = e.target || e.srcElement
    // variable target has your clicked element
        innerId = target.id;
        //  do your stuff here. 
        alert("Clicked!");
    
    }
    
    0 讨论(0)
  • 2020-12-19 07:51

    I think this is what you mean?

    var test = document.getElementById('test');
    
    function whatClicked(evt) {
      alert(evt.target.id);
    }
    
    test.addEventListener("click", whatClicked, false);
    div#test {
      width: 300px;
      height: 200px;
      position: relative;
      display: block;
      border: 1px solid blue;
    }
    
    div#test div,
    div#test span {
      display: block;
      position: absolute;
      border: 1px solid red;
    }
    
    div#inner1 {
      top: 15px;
      left: 15px;
      height: 15px;
      width: 15px;
    }
    
    span#inner2 {
      top: 65px;
      left: 65px;
      height: 15px;
      width: 15px;
    }
    
    div#inner3 {
      top: 155px;
      left: 155px;
      height: 15px;
      width: 15px;
    }
    <div id="test">
      <div id="inner1"></div>
      <span id="inner2"></span>
      <div id="inner3"></div>
    </div>

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