這個問題的大多數答案都給出了類似的解決方案:
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';
但只是改變位置,將整數轉換為字串并進行一些連接,這不是很昂貴嗎?
我認為瀏覽器可能會進行完全相反的計算以再次獲取整數值。
uj5u.com熱心網友回復:
現在在現代瀏覽器中連接字串并不昂貴。這是一個將元素移動到(另一個)位置的工廠,使用一個小助手將數字轉換為單位。
// 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369361.html
標籤:javascript dom css-位置 字符串连接
上一篇:如何在Document.createElement()中使用特殊字符-VBADOMXML
下一篇:在我的手機上運行Flutter應用程式時,任務':app:generateDebugBuildConfig'執行失敗
