简体   繁体   中英

window.getSelection().baseOffset is wrong

If you select any text below beginning at the first character H , it will say the baseOffset of the selection is 5 . In my real-life case it says 7 . How do I correct this?

 setInterval(()=>{ console.log(window.getSelection().baseOffset); }, 250);
 <!DOCTYPE html> <html> <body> <div id='main'data-alignment="center"> Hello World! </div> </body> </html>

The result is correct, you have exactly 5 space characters between the end of <div id='main'data-alignment="center"> and the H , these will be counted as offset.

To avoid that, you can wrap your TextNode in a <span> element so that there is no offset.

Also, baseOffset is still not in the official specs, better use anchorOffset which I think does approximately the same thing (but is supported in all browsers).

 document.onselectionchange = ()=>{ console.log(window.getSelection().anchorOffset); };
 <!DOCTYPE html> <html> <body> <div id='main'data-alignment="center"> <span>Hello World!</span> </div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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