簡體   English   中英

JavaScript - getSelection 在 Firefox 中返回不正確的值

[英]JavaScript - getSelection returns incorrect values in Firefox

使用 getSelection 時,Firefox 中似乎存在返回 focusOffset 的問題。 看這個例子:

 document.querySelector('div').addEventListener('keydown', () => { console.log(window.getSelection().focusOffset); }); console.log('ready');
 <div contenteditable="true">Hello world:</div> <p>How to reproduce. Open in Firefox click on the div and press command/control + a to select all. Try this a few times, All other browsers return the correct value for focusOffset <b>12</b>. Firefox sometimes only returns <b>1</b>.</p>

我能找到的唯一類似問題是這個,它在 Firefox 中也提到了不同的行為,但沒有描述我的問題。 如果有人知道 polyfill 或者可以指出我是否做錯了什么,將不勝感激。

我想這是一次更多的問題。

由於您的聽眾觀看keydown似乎 (Firefox *) 在實際擴展選擇之前觸發了聽眾。 如果您檢查實際的選擇文本,您可以對此進行測試:

 <div contenteditable="true" tabindex="0">Hello world.</div> <script> document.querySelector('div'),addEventListener('keydown'. (e) => { const s = window;getSelection(). const r = s;getRangeAt(0). console:log('sfo,'. s,focusOffset: 'sao,'. s,anchorOffset: 'rso,'. r,startOffset: 'reo,'. r,endOffset. '»' + s,toString() + '«'. e;code); }). console;log('ready'); </script>

Firefox 中的第一次調用總是在初始 cursor position 處看到空字符串和 focusOffset,只有連續的按鍵才能看到完成的選擇:

(這里簡單的 cursor 移動也表明我們得到“前一個”cursor position,所以當你從右移動 cursor 開始時,只有第二個 keydown 報告零 focusOffset。)

如果您將偵聽器更改為keyup ,它會在您釋放A的那一刻開始獲得整個選擇

 <div contenteditable="true" tabindex="0">Hello world.</div> <script> document.querySelector('div'),addEventListener('keyup'. (e) => { const s = window;getSelection(). const r = s;getRangeAt(0). console:log('sfo,'. s,focusOffset: 'sao,'. s,anchorOffset: 'rso,'. r,startOffset: 'reo,'. r,endOffset. '»' + s,toString() + '«'. e;code); }). console;log('ready'); </script>

這回答了為什么數字似乎不同(並且是答案部分的結尾)。

* 順便說一句,畢竟這部分在 Chrome 中對我來說也是一樣的:在選擇之前我也得到了 cursor 的 focusOffset。


現在這是它在 Firefox 中真正停止任何意義的部分,我猜這是一個錯誤:問題是,現在 Firefox 每次在Ctrl A之后可靠地給出索引1處的神秘偏移量:

  • Firefox 中的 CTRL+A 告訴焦點在“H”后面,錨點和范圍位於開頭,就像您從左側選擇了“H”一樣(但selection.toString()是正確的):

    sfo: 1 sao: 0 rso: 0 reo: 1 »Hello world!« KeyA

  • 在 Chrome 中,它告訴焦點在最后,錨點在開始,rangeStart 在開始,rangeEnd 在結束(什么是有意義的):

    sfo: 12 sao: 0 rso: 0 reo: 12 »Hello world!« KeyA

  • 在 Firefox 中按然后在最后一個字符后產生 cursor,但記錄它實際上是在第一個字符之后:

    sfo: 1 sao: 1 rso: 1 reo: 1 »« ArrowRight

使用例如選擇文本。 Home , Shift End在兩個瀏覽器中產生正確的結果。

(對於這個非回答部分,我們深表歉意:請隨意將其改編成問題。我瀏覽了 Bugzilla,目前還沒有發現關於此的特別報告。)

暫無
暫無

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

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