【问题标题】:javascript change position of element without string concatenationjavascript在没有字符串连接的情况下更改元素的位置
【发布时间】:2021-12-21 07:24:16
【问题描述】:

这个问题的大多数答案给出的解决方案类似于:

let x_pos=42, y_pos=43;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';

但是只是改变位置,将整数转换为字符串并进行一些连接,这不是很昂贵吗?

我认为浏览器可能会进行完全相反的计算以再次获取整数值。

【问题讨论】:

  • 你为什么认为它们是“昂贵的字符串连接”?
  • 字符串连接需要更多的 cpu 周期,因为只是一个分配,单位缩放,可以像 d.setX(42, "px");这仍然比上面的方法更快
  • 这些天浏览器的优化非常好。除非您对代码做一些疯狂的事情,否则几个字符串连接不会占用 CPU 资源。
  • 这不会发生,因为您需要数字和单位。高度怀疑小连接是否会导致您的代码变慢。 premature optimization
  • 浏览器解析字符串所花费的时间与重新布局和重新绘制受影响区域所花费的时间相比可以忽略不计,即使在正常情况下速度如此之快以至于您永远不会注意到它(除非您的文档非常非常复杂)。

标签: javascript dom css-position string-concatenation


【解决方案1】:

现在concatenate strings in modern browsers 并不贵。这是一个将元素移动到(另一个)位置的工厂,使用一个小助手将数字转换为单位。

// factory to avoid recreating [number2Unit] for every call and 
// and delegate the actual styling to small methods.
function moveElToFactory(ux = `px`, uy = `px`) {
  const number2Unit = (nr, unit) => `${nr}${unit}`;
  const moveX = (el, x, unit) => el.style.left = number2Unit(x, unit);
  const moveY = (el, y, unit) => el.style.top = number2Unit(y, unit);
  
  return (el, x, y, uX = ux, uY = uy) => {
    el.style.position = `absolute`;
    y && moveY(el, y, uY);
    x && moveX(el, x, uX);
  }
}

// demo
const moveElTo = moveElToFactory();
setTimeout(() => {
  const [d1, d2, d3] = [
    document.querySelector('#div1'),
    document.querySelector('#div2'), 
    document.querySelector('#div3')]
  moveElTo(d1, 42, 43);
  d1.textContent += ` [x, y] ${d1.style.left}, ${d1.style.top}`;
  moveElTo(d2, 15, 50, `vw`, `%`);
  d2.textContent += ` [x, y] ${d2.style.left}, ${d2.style.top}`;
  moveElTo(d3, ...[,35,,`%`]); 
  d3.textContent += ` [x, y] 0, ${d3.style.top}`; }, 1000);
<div id="div1">where am I (div#div1)?</div>
<div id="div2">And where am I (div#div2)?</div>
<div id="div3">And I (div#div3) am where?</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2011-05-18
    • 1970-01-01
    相关资源
    最近更新 更多