首页 > 解决方案 > 有没有办法将 $this 从 jquery 转换为 javascript?

问题描述

最近在stackoverflow上摆弄了这个问题:

围绕圆圈动态排列元素

但是这个解决方案包括 jquery 和 $(this) 关键字。我想转换这段代码:

function distributeFields(deg) {
    deg = deg || 0;
    var radius = 200;
    var fields = $('.field'), container = $('#container'),
        width = container.width(), height = container.height(),
        angle = deg || Math.PI*3.5, step = (2*Math.PI) / fields.length;
    fields.each(function() {
        var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2);
        var y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2);
        if(window.console) {
            console.log($(this).text(), x, y);
        }
        $(this).css({
            left: x + 'px',
            top: y + 'px'
        });
        angle += step;
    });
}

这是我在陷入 ($this) 关键字之前尝试做的事情:

function distributeFieldsJS(deg){
  deg = deg || 0;
  let radius = 200;
  let fields = document.querySelectorAll('.field'), 
  container = document.querySelector('#container'),
  width = container.width(), height = container.height(),
  angle = deg || Math.PI * 3.5, 
  step = (2*Math.PI) / fields.length;
  })

标签: javascriptjquerycss

解决方案


它在 jQueryeach回调中,所以它指的是当前被迭代的元素,所以你只需要做

for (const field of fields) {
  // refer to `field` here
}

并且field将是本机 DOM 元素。(就像$(this)引用 jQuery 中包装的相同元素一样)。

getBoundingClientRect会给你它的尺寸。 field.textContent将检索其文本。field.style将为您提供元素的CSSStyleDeclaration


推荐阅读