簡體   English   中英

在DIV中選擇文本,突出顯示文本時更改按鈕(未突出顯示時取消選擇)

[英]Selecting text within a DIV, changing button when text is highlighted (deselect when its unhighlighted)

我從小提琴那里得到了這個腳本: http : //jsfiddle.net/83T7U/5/ 當在特定DIV中選擇了一些文本時,它將按鈕名稱從“答復”更改為“報價”。 但是,它僅適用於明文(即沒有任何跨度,粗體,斜體等標記)。

我想更改此腳本,使其也可以與HTML標記一起使用。 因此,需要更改方法,最簡單的方法應該是定位按鈕,而不是DIV中的父/子文本。

因此,我創建了一個新腳本(但未完成): http : //jsfiddle.net/c8UbV/ ,當DIV中的文本突出顯示時,應將按鈕名稱從“答復”更改為“引用”(並進行更改)取消突出顯示文字時返回“回復”。 但是它不起作用(因為它不完整...)。 如何使其正常工作?

HTML

<div id="m2560" class="yellow">DIV1: First <span style="color:red">some red text for</span> you to select
<br>
<button id="msg2560">Reply</button>
</div>
<br>
    <div id="m2900" class="green">DIV2: <b>Second some bold</b> test text for you to select
<br>
<button id="m2900">Reply</button>
</div>
<br>
    <div id="msg3022" class="blue">DIV3: <i>Third some italic test</i> text for you to select
<br>
<button id="msg3022">Reply</button>
</div>

JavaScript的:

function changeButton() {
// for now this script only checks if text is selected
    var text = "";
    if (typeof window.getSelection != "undefined") {
//? it should probably be document.GetElementById('button_id').innerHTML='Quote';
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
//? it should probably be document.GetElementById('button_id').innerHTML='Quote';
    }
    return text;
}   
    document.GetElementById('msg***').onclick = changeButton;

您擁有的原始腳本距離不遠。 我建議使用

生成的代碼比您獲得的代碼更長,但更具邏輯性,模塊化和可讀性。

另外,它是document.getElementById()而不是document.GetElementById()

演示: http//jsfiddle.net/9zXg6/6/

鏈接答案中未包含的代碼:

function getSelfOrAncestorWithClass(node, theClass) {
    while (node) {
        if (hasClass(node, theClass)) {
            return node;
        } else {
            node = node.parentNode;
        }
    }
    return null;
}

暫無
暫無

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

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