2015-04-02 181 views
0

我有以下javascript,它在選擇文本並單擊按鈕時突出顯示文本。getSelection突出顯示

$('.highlight').on("click", function (e) { 
    selected = getSelection(); 
    range = selected.getRangeAt(0); 
    newNode = document.createElement("span"); 
    newNode.setAttribute("class", "highlighted"); 
    range.surroundContents(newNode); 
}); 
function getSelection() { 
    var seltxt = ''; 
    if (window.getSelection) { 
     seltxt = window.getSelection(); 
    } else if (document.getSelection) { 
     seltxt = document.getSelection(); 
    } else if (document.selection) { 
     seltxt = document.selection.createRange().text; 
    } else return; 

    return seltxt; 
} 

但是,這會在我的p標記中創建很多凌亂的span類。是否可以立即對選定的文本進行着色而不必將其包裹在一個範圍中?

的另一個原因是這樣做的,我要檢查選中的文本是否已經有一個黃色的背景,如果是把它透明的(也許是兩種顏色之間切換)

+0

如果你想這樣的事情發生,當你選擇,你能做到這一點的'CSS' – lshettyl 2015-04-02 13:44:00

+0

感謝@LShetty我會怎麼做。我想讓它保持背景顏色(不只是在選擇時)。例如電子書中的高亮工具。 – 2015-04-02 14:01:05

+0

代碼格式 – Khalid 2015-04-02 16:24:41

回答

0

怎麼這樣呢?請記住,這會將樣式片段添加到您的網頁,您可能希望根據自己的要求將其移除。現在,它也會突出顯示選擇的文本,否則。

$(".highlight").on("click", function() { 
 
    !$("#selection").length && $("<style id=\"selection\">::-moz-selection { background: #111; color: #fff; } ::selection { background: #111; color: #fff; }</style>").appendTo("head"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>This is some text. Select me to see my color and background color change!</p> 
 

 
<button class="highlight">Click Me</button>

注意,::selection已經removed from the spec。它可能無法可靠地爲所有用戶工作。

enter image description here

+0

感謝@LShetty,但背景顏色不會保留 - 只要您刪除選擇背景顏色,我希望這樣,當你按下按鈕時,背景顏色會發生變化,並保持不確定狀態(突出顯示一個真實的頁面) – 2015-04-02 14:17:03

+1

我不認爲如果沒有將選擇包裹在標籤中就可以完成! – lshettyl 2015-04-02 14:22:23

+0

啊我看到了 - 這真是一種恥辱,只有當你突出顯示同樣的東西幾次,因爲它進行了所有重疊的span標籤的加載 – 2015-04-02 14:23:36