簡體   English   中英

element.getBoundingClientRect 不斷返回初始值

[英]element.getBoundingClientRect constantly returning the initial value

我有一個帶有文本的 div,它跟隨光標(在mousemove事件中設置它的transform:translate )。

它做的另一件事是,如果彈出窗口超過視口的右邊界,則相應地設置 maxWidth - 文本 div 變得更薄,但更高。

雖然上述效果很好,但出於某種原因div.getBoundingClientRect拒絕在應用最大寬度后報告文本 div 的高度 - 它不斷返回初始值。 不過,此問題僅發生在腳本中。 我應該從控制台查詢它,返回正確的(更新的)高度。 為什么?

 const div = document.querySelector("#div"); const p = document.querySelector("#p"); document.addEventListener("mousemove", e => { div.style.maxWidth = "400px"; div.style.transform = `translate(${e.pageX}px, ${e.pageY}px)`; const bRect = div.getBoundingClientRect(); p.innerHTML = bRect.height; if (document.documentElement.clientWidth < bRect.right) { div.style.maxWidth = document.documentElement.clientWidth - e.pageX + "px"; }; });
 #div { max-width: 400px; display: grid; place-items: center; outline: 1px solid black; position: absolute; pointer-events: none; word-break: break-all; } html, body { height: 100%; margin: 0; padding: 0; overflow: auto; }
 <p id="p"></p> <div id="div"> Here is some text.Here is some text.Here is some text.Here is some text.Here is some text.Here is some text. </div>

請簡單地將光標移向右邊界。

在您的代碼中,您正在計算BoundingClientRect之后更改 div 的最大寬度。 所以它首先輸出初始值,然后才改變最大寬度,從而改變高度。

const bRect = div.getBoundingClientRect();
p.innerHTML = bRect.height;

if (document.documentElement.clientWidth < bRect.right) {
    div.style.maxWidth = document.documentElement.clientWidth - e.pageX + "px";
}

如果要在 div 調整大小打印高度,則必須再次調用getBoundingClientRect

 const div = document.querySelector("#div"); const p = document.querySelector("#p"); document.addEventListener("mousemove", e => { div.style.maxWidth = "400px"; div.style.transform = `translate(${e.pageX}px, ${e.pageY}px)`; const bRect = div.getBoundingClientRect(); if (document.documentElement.clientWidth < bRect.right) { div.style.maxWidth = document.documentElement.clientWidth - e.pageX + "px"; } p.innerHTML = div.getBoundingClientRect().height; });
 #div { max-width: 400px; display: grid; place-items: center; outline: 1px solid black; position: absolute; pointer-events: none; word-break: break-all; } html, body { height: 100%; margin: 0; padding: 0; overflow: auto; }
 <p id="p"></p> <div id="div"> Here is some text.Here is some text.Here is some text.Here is some text.Here is some text.Here is some text. </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM