Javascript:如何在光标的当前位置插入域?

问题描述 投票:0回答:2

能否以小书签或类似形式的Javascript在光标位置插入当前页面的域?怎么样?

对同时插入stackoverflow.comwww.stackoverflow.comwww都感兴趣。

((用例:我在此处在这里写一个问题,光标位于标题文本字段或问题正文文本区域中,并且我想在光标的当前位置插入域名)。

javascript bookmarklet
2个回答
0
投票

[聚焦文本区域时,单击书签,然后使用document.activeElement识别文本区域,并使用.slice的值与window.location.origin串联:

javascript: (() => {
  const textarea = document.activeElement;
  const { selectionStart } = textarea;
  textarea.value = textarea.value.slice(0, selectionStart) + window.location.origin + textarea.value.slice(selectionStart);
})();

0
投票

[此功能为键盘快捷键ctrl + g添加了一个事件侦听器,并将当前URL插入到用于输入和文本区域标签的光标位置

const fields = ['INPUT','TEXTAREA'];
function doc_keyUp(e) {
   if (e.ctrlKey && e.keyCode == 71) {
    // call your function to do the thing
    console.log(document.activeElement)
    if(fields.includes(document.activeElement.tagName)){
      let myField = document.activeElement;
      let startPos = myField.selectionStart;
      let endPos = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos)
            + window.location.href
            + myField.value.substring(endPos, myField.value.length);
      }
   }
}
// register the handler
document.addEventListener('keyup', doc_keyUp, false);
© www.soinside.com 2019 - 2024. All rights reserved.