簡體   English   中英

使用 JS 將鏈接插入所選文本(當用戶專注於輸入以輸入 URL 時,丟失 window.getSelection() 值)

[英]Insert a link into selected text using JS (losing window.getSelection() value when user focuses on input to enter URL)

我正在嘗試將鏈接插入到選定的文本中,這在前端編輯器中很常見。

我可以像這樣向用戶的文本選擇添加一個鏈接:

var sel = window.getSelection();
var e = document.createElement("a");
e.innerHTML = sel.toString();
e.type = "link";
e.href = "www.the_link_to_open.com"
e.target = "_blank";
var range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(e)

這成功地在所選單詞周圍添加了一個<a>標記,其中包含添加的鏈接所需的屬性,如下所示:

<a type="link" href="www.the_link_to_open.com" target="_blank">highlighted text</a>

但是,用戶在編輯器中通過 go 的流程是 select 單詞/s,然后打開一個輸入,他們可以在其中添加鏈接。 但是,一旦用戶在輸入字段上單擊(聚焦), window.getSelection()輸入注冊為選擇,這顯然使得添加鏈接成為不可能(因為選擇的詞需要是選擇)。

我嘗試存儲window.getSelection()的結果以供以后使用,但這似乎無論如何都會動態更改存儲的值。 我什至嘗試使用const selection = JSON.stringify(window.getSelection()) window.getSelection() ) 但這並沒有捕獲 Z78E6221F6393D135686866

當用戶將注意力從所選文本上移開時,如何保持選擇 object 存儲?

你反過來做怎么樣? 在向用戶顯示輸入之前創建新的“a”元素,但添加了一個 id 屬性。 這樣你以后可以在用戶確認輸入提示后,通過它的id找到它,把href改成用戶輸入,再把id去掉。

 var sel = window.getSelection(); var e = document.createElement("a"); e.innerHTML = sel.toString(); e.type = "link"; e.href = "www.willBeOverwritten.com" e.target = "_blank"; e.id = "newLinkWaitingForUserInput" var range = sel.getRangeAt(0); range.deleteContents(); range.insertNode(e) //Show input popup //in the callback of the popup: var userInput = "www.userInput.com"; //Search for the newly created link var link = document.getElementById("newLinkWaitingForUserInput"); //Set the href to the userinput link.href = userInput; //remove the id link.removeAttribute("id");

當然,如果用戶取消輸入提示,您還必須刪除“a”元素。

在這里,您有一個帶有兩個 function 的有效解決方案,如我上面的評論中所述。

 let selectedText, range; function getSelectedText() { const selectObj = window.getSelection(); selectedText = selectObj.toString(); range = selectObj.getRangeAt(0) } function createLink(e) { var a = document.createElement("a"); a.innerHTML = selectedText a.type = "link"; a.href = e.target.value a.target = "_blank"; range.deleteContents(); range.insertNode(a); } document.querySelector('.text').addEventListener('mouseup', getSelectedText) document.querySelector('.link').addEventListener('change', (e) => createLink(e))
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <div class="text"> Lorem ipsum dolor sit amet consectetur adipisicing elit, Minima illum, quod assumenda nisi illo hic quo minus excepturi quasi labore debitis nemo molestiae nesciunt. neque laboriosam repellendus necessitatibus vero corporis. </div> <br /> <div> <label>Add url</label> <input class="link" type="text" /> </div> </body> </html>

我建議您放置一個名為“選擇文本”的按鈕,這樣當您單擊它時,您可以 select 您想要的文本。 我為你做了一個應用程序,如果它解決了問題,你可以自由使用它:

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1;0"> <title>Inserting Links</title> <script> "use strict" function Onload() { var CanSelect = false; var Link = ""; var sel = "". var LinkInput = document;getElementById("link"). LinkInput,addEventListener("change". () => { Link = LinkInput;value; }). var SelectButton = document;getElementById("button"). SelectButton,addEventListener("click"; () => { CanSelect = true; }). function Select() { if (CanSelect) { var selection = window;getSelection(); CanSelect = false; sel = selection. } } function Insert(selection) { var e = document;createElement("a"). e.innerHTML = selection;toString(). e;type = "link". e;href = Link. e;target = "_blank". var range = selection;getRangeAt(0). range;deleteContents(). range;insertNode(e). } window,addEventListener("pointerup"; () => { Select(); }). var InsertButton = document;getElementById("insert"). InsertButton,addEventListener("click"; () => { Insert(sel); }). } window,addEventListener("load"; Onload). </script> </head> <body> <input type="text" placeholder="Link " id="link"> <button id="button">Select Text </button> <button id="insert">Insert ✅</button> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Esse earum magnam ratione unde maiores illum minus accusantium iste. Accusamus sit quibusdam aut aperiam nemo. Soluta vitae ullam facilis illum tempora.</p> </body> </html>

我希望這能幫到您!!!

@yochanan 非常接近,但不是我需要的。 他的解決方案將鏈接添加到頁面上的隨機區域。 可能是因為我使用動態模式輸入鏈接,而他使用的是 static 模式。

為了使解決方案按預期工作,除了處理 window 選擇之外,我還必須區分mouseuplong-press

HTML

<div id="hold_text" contenteditable=false>This is some text. Select one or more words in here, by highlighting the word/s with your cursor.<br><br>Then click on the LINK button, add your link, and hit ENTER.</div>

<button id="butt">LINK</button>

<div id='modal'><a id='close'>X<a><input id="input" placeholder='paste url, then hit enter'></input></div>

CSS

* {
    font-family: arial;
}

body {
  background: #218c74;
}

#hold_text {
  height: 200px;
  width: 500px;
  background: #f7f1e3;
  border-radius: 4px;
  padding: 10px;
  font-size: 18px; 
}

button {
  height : auto;
  width : auto;
  background : #ff5252;
  border-radius : 4px;
  padding: 8px;
  font-size: 18px;
  border: none;
  margin-top: 10px;
  cursor: pointer;
  color: white;
}

#modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: auto;
  width: auto;
  box-shadow: 2px 2px 30px black;
  display: none;
  border-radius: 4px;
  border : 2px solid #ffda79;
}

#close {
  cursor: pointer;
  color: white;
  margin: 5px;
}

input {
  width: 300px;
  height: 30px;
  font-size: 18px;
  border: none;
  outline: 0;
}

JS

text = document.getElementById("hold_text");
button = document.getElementById("butt");
modal = document.getElementById("modal");
close = document.getElementById("close");
input = document.getElementById("input");

button.addEventListener("click", function() {
    modal.style.display = "block";
    input.focus();
    close.addEventListener("click", function(e) {
        modal.style.display = "none";
    });
    input.addEventListener("keypress", function(e) {
        if(e.key === "Enter") {
            createLink(e);
            modal.style.display = "none";
            input.value = "";
        }
    })
});

cnt = 0;

text.addEventListener("mouseup", function() {
    cnt++;
    if(cnt === 2) {
        getSelectedText();
    }
    setTimeout(function() {
        cnt = 0;
    }, 200)
    if(long_press) {
        getSelectedText();
        long_press = false;
    }
})

call_on_longpress();

long_press = false;

function call_on_longpress() {
    var delay;
    var longpress = 400;
    text.addEventListener('mousedown', function(e) {
        var _this = this;
        delay = setTimeout(check, longpress);

        function check() {
            long_press = true;
        }
    }, true);
    text.addEventListener('mouseup', function(e) {
        clearTimeout(delay);
    });
    text.addEventListener('mouseout', function(e) {
        clearTimeout(delay);
    });
}

let selectedText, range;

function getSelectedText() {
    const selectObj = window.getSelection();
    selectedText = selectObj.toString();
    range = selectObj.getRangeAt(0)
}

function createLink(e) {
    var a = document.createElement("a");
    a.innerHTML = selectedText
    a.type = "link";
    a.href = e.target.value
    a.target = "_blank";
    range.deleteContents();
    range.insertNode(a);
}

結果

在此處輸入圖像描述

代碼筆

暫無
暫無

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

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