繁体   English   中英

javascript在没有字符串连接的情况下更改元素的位置

[英]javascript change position of element without string concatenation

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

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';

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

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

现在在现代浏览器中连接字符串并不昂贵。 这是一个将元素移动到(另一个)位置的工厂,使用一个小助手将数字转换为单位。

 const moveElTo = moveElToFactory(); setTimeout(() => { moveElTo(document.querySelector('#div1'), 42, 43); moveElTo(document.querySelector('#div2'), 15, 50, `vw`, `%`); moveElTo(document.querySelector('#div3'), ...[,35,,`%`]);}, 1000); // factory to avoid recreating number2Unit for every call 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); } }
 <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM