mouseup 上的 window.getSelection() 返回上一个选择

son*_*nia 6 javascript contenteditable

单击已选择的文本时,它会被取消选择并出现光标。这就是我的问题出现的地方 - 在 mouseup 事件上, window.getSelection() 仍然返回先前的选择(范围)。如何获得正确的选择(光标)?

Ler*_*ang 1

这是一个经过验证的解决方案:

function getSelectionAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(window.getSelection().toString());
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await getSelectionAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();
Run Code Online (Sandbox Code Playgroud)

参考:

  1. 异步函数