点击事件后获取子元素的位置

时间:2017-07-27 14:37:02

标签: javascript arrays html5 css3

我想编写一个程序,它会返回父元素中的子元素位置,但是我遇到了问题。我尝试编写以下代码,但它没有按预期工作;它返回了click事件,而不是返回位置值。这是我尝试做的事:
(P.S我想在原始JS中解决这个问题)

 (function () {
    // body...

        var x = document.getElementsByClassName("bubble");

        for(var i=0; i<x.length; i++) {

            x[i].addEventListener('click', function(i){


                console.log(i);


            });



        }

})();

HTML:

<div id=holder>
<div class="bubble"></div>
<div class="bubble"></div>
<div class="bubble"></div>
<div class="bubble"></div>
</div>

3 个答案:

答案 0 :(得分:1)

监听器函数中的

i代表整个元素及其事件,而不是index循环中的for。记录它可能会使浏览器崩溃/滞后。

我建议你使用Array#forEach的ES6宝藏。

const elems = document.querySelectorAll('#holder .bubble');

Array.from(elems).forEach((v, i) => v.addEventListener('click', () => {
   console.log(`Child position: ${i}`);
}));
<div id="holder">
  <div class="bubble">a</div>
  <div class="bubble">b</div>
  <div class="bubble">c</div>
  <div class="bubble">d</div>
</div>

但是,如果您真的想要使用for循环,请不要将任何参数传递到您的侦听器函数中,并将循环中的var i更改为let i

const x = document.getElementsByClassName("bubble");

for (let i = 0; i < x.length; i++) {
  x[i].addEventListener('click', function() {
    console.log(i);
  });
}
<div id="holder">
  <div class="bubble">a</div>
  <div class="bubble">b</div>
  <div class="bubble">c</div>
  <div class="bubble">d</div>
</div>

答案 1 :(得分:1)

如果您想在x和y坐标中找到位置,可以执行以下操作:

  1. 确保父div(#holder)位于
  2. 使用offsetLeftoffsetTop
  3. 如果您想在数组位置找到位置,可以使用

    Array.prototype.indexOf.call(collection, element)

    &#13;
    &#13;
    (function() {
      // body...
      var x = document.getElementsByClassName("bubble");
    
      for (var i = 0; i < x.length; i++) {
    
        x[i].addEventListener('click', function(a) { // change the variable name here otherwise you have a local var i conflicting with the loop var i
    
          console.log(this.offsetLeft, this.offsetTop); // this is the element clicked 
          
          console.log(Array.prototype.indexOf.call(x, this) + 1); // this is the position as an index (plus 1)
        });
      }
    
    })();
    &#13;
    #holder {
       position:relative;  /* position the parent */
    }
    &#13;
    <div id="holder">
      <div class="bubble">1</div>
      <div class="bubble">2</div>
      <div class="bubble">3</div>
      <div class="bubble">4</div>
    </div>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

您可以使用此功能:https://developer.mozilla.org/en-US/docs/DOM/element.getBoundingClientRect

https://jsfiddle.net/dt1224Ld/

(function () {
// body...

    var x = document.getElementsByClassName("bubble");

    for(var i=0; i<x.length; i++) {

        x[i].addEventListener('click', function(i){

                    var element = this.getBoundingClientRect();

            console.log(element.top, element.right, element.bottom, element.left);


        });



    }

})();