簡體   English   中英

單擊div類時將文本插入文本字段

[英]Inserting text into a text field when a div class is clicked

我現在正在創建此提交系統。 我想創建它以便插入一些文本(例如[b] [/b] ),當單擊div時。 這是我們正在使用的示例:

<div class="insertBBC" title="Bold Text" onClick="moveNumbers([b][/b])" id="bold">
                        <p>B</p>    
                    </div>  
                    <div class="insertBBC" title="Italic Text">
                        <p>I</p>
                    </div>
                    <div class="insertBBC" title="Bullet Points">
                        <p>BP</p>

等等...
我也希望這樣做,以便當文本字段中已經有內容時,它也不會從那里刪除任何內容,而且,它應該在光標所在的位置添加[b][/b]標簽。 選中文本后,會將[b]標記放在所選內容的前面,並將[/ b]標記放在后面。 有點像BBC作品。 我不知道如何實現這些目標,我已經研究了很長時間,我看到人們在說用JQuery唯一可行的方法,但我不知道Jquery還是JS ,所以是的。 如果可能的話。

另外,這些是文本框。 其中有兩個,我想插入當前處於活動狀態的一個。

<br><textarea name="newPost" placeholder="Post Preview(Will Be Displayed on the Index Page)" cols="100"  rows="10"/></textarea><br>
<br><textarea name="newPostPreview" placeholder="Post Text" cols="100"  rows="10"/></textarea>

有線索嗎? 謝謝 :)

不幸的是,您唯一的選擇是使用jQuery或Javascript(或其他一些瀏覽器端庫)。 PHP僅處理服務器端代碼,並且可以吐出您要使用的html字段,但是在將頁面加載到瀏覽器后,它無法與元素進行交互。

我無法向您解釋如何使用jQuery,但僅值得立即開始學習它。 用它做簡單的事情很容易,所以不要被嚇到。

這是我建議的入門方法:使用此標記加載最新的jQuery庫:

<script src="http://code.jquery.com/jquery-latest.js"></script>

然后,您將定位適當的按鈕並在單擊它們時執行一些操作:

$("#boldButtonID").click(function(){
    //get the index of the cursor
    //select the word that the cursor is on by stopping at the space (" ") character in either direction, then insert [b] and [/b] in the appropriate locations.
}

您還可以通過使用此功能獲得所選的文本 ,我在這里得到了: 獲取突出顯示/選定的文本

function getSelectionText() {
var text = "";
if (window.getSelection) {
    text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
}
return text;
}

然后,您可以使用函數.before()。html(“ [b]”)和.after()。html(“ [/ b]”)將標簽放置在需要的位置。

我希望這有助於您了解需要做的事情。

干杯!

暫無
暫無

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

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