Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index

前端 未结 4 1820
無奈伤痛
無奈伤痛 2020-12-03 04:54

What is problem here?

if ( window.getSelection() ) 
  EditField = window.getSelection().getRangeAt(0);

throws error:

<
4条回答
  •  隐瞒了意图╮
    2020-12-03 05:47

    The exact way to address this problem (like 90% of everything in JavaScript) is object detection; selection related isn't as straight forward of course:

    if (window.getSelection().rangeCount >= 1) {var r = window.getSelection().getRangeAt(0);}
    

    To test throw window.getSelection().rangeCount in to a console when there is no selected text and it'll return 0; with a selection it'll return 1. I am not sure however if and how you could manage to get it to return 2 or greater.

提交回复
热议问题