检索到动态添加元素顶部的距离 [英] Retrieving Distance to Top of a Dynamically Added Element

查看:57
本文介绍了检索到动态添加元素顶部的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我是在动态添加按钮.添加的每个按钮都有一个不同的类.我设置了样式规则,以便将每个后续按钮放置在上一个按钮下方.因此,我需要找到每个按钮到顶部的距离,以便以后将其用于逻辑.

In my case, I'm adding buttons dynamically. Each button that is added has a different class. I have style rules set up so that each subsequent button will be placed below the previous button. So, what I need is to find the distance to top to each button in order to use it later for logic.

我尝试了以下两种方法来检索到顶部的距离.第一个使用本机javascript,我将其存储为:var = h.第二次,我尝试了更多的D3方法,并将其存储为:var = h2.

I tried two ways to retrieve the distance to top in the code below. the first using native javascript, which I stored as: var = h. The second time around I tried more of a D3 approach, which I stored as: var = h2.

d3.select('body').append('button')
    .text('X')
    .attr('id','button'+(intCount+1))
    .attr('class',choice+'1')
    .on('click', function(d,i) {
    var t = d3.select(this).attr('id')
    var c = d3.select(this).attr('class')
    var h = document.getElementByID(t).offsetTop;
    var h2 = d3.select(this).offsetTop
      var thisChoice = choice;

      d3.selectAll('.' + t).remove();
      d3.selectAll('.'+ thisChoice+'1').remove();
      intCount -= 1;
      count -= .7;
    });

这两个都在控制台日志中返回null.哦,实际上,一个给了我一个错误,另一个给了我未定义的提示.

Both of these return null in the console log. Oh actually, one gave me an error, and the other returned undefined.

推荐答案

在您的 D3方法中,您只需要this,而不是d3.select(this),这将返回D3选择:

In your D3 approach you only need this, not d3.select(this), which will return a D3 selection:

d3.select('body').append('button')
  .text('X')
  .on('click', function() {
    var h2 = this.offsetTop;
    console.log(h2)
  });

<script src="https://d3js.org/d3.v4.min.js"></script>

关于您的原生JS方法,您有一个错字:它是getElementById,而不是getElementByID:

Regarding your native JS approach, you have a typo: it is getElementById, not getElementByID:

d3.select('body').append('button')
  .text('X')
  .attr("id", "foo")
  .on('click', function() {
    var t = d3.select(this).attr("id");
    var h = document.getElementById(t).offsetTop;
    console.log(h)
  });

<script src="https://d3js.org/d3.v4.min.js"></script>

这篇关于检索到动态添加元素顶部的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆