עריכת טקסט מסומן
מתוך וויקי
עריכת טקסט מסומן מ-textarea
לא פעם קורה שאנחנו רוצים לאפשר למשתמש באתר (במסגרת הודעות בפורומים וכדומה) לעצב את הטקסט הנשלח. יש לנו כמה אפשרויות כדי לבצע את זה:
1. להשתמש בדרך הפשוטה של הוספת תג פותח בסוף ה-textarea (ע"י לחיצה על כפתור) - המשתמש יכניס טקסט ויסגור את התג ע"י לחיצה על כפתור נוסף. כך תיראה הפונקציה:
function addTags(tag, textAreaId)
{
document.getElementById(textAreaId + "").value += tag;
}
יתרון:- פשוט ועובד בכל הדפדפנים.
חיסרון: - יכול להיות שהמשתמש לא יקפיד לסגור תגיות .
2) שימוש באובייקט ה-Selection של IE ובשלוש תכונות של textarea הנתמכות רק במוזילה (וכמובן גם ב-Netscape 6 ומעלה ובכל דפדפן מבוסס גקו). ע"י שימוש בנ"ל אנו יכולים לתת למשתמש אפשרות לסמן טקסט מסויים ואז לעטוף אותו בתגיות העיצוב שהמשתמש בחר או שהמשתמש פשוט יכתוב בין תגית הפתיחה והסגירה שהוספנו אוטומטית ל-textarea. הפונקציה תיראה כך:
function addtoForm(openTag, closeTag, textAreaId)
{
// Add tags code to textarea
var txtAr = document.getElementById(""+textAreaId), oRange;
txtAr.focus();
if (document.selection && document.selection.createRange)
{
oRange = document.selection.createRange();
// Create Range object form the selected Text
if (oRange.parentElement()==txtAr)
{
// Check if the parent of the Range object is our textarea
// add the tags before and after the selected text
oRange.text = openTag+oRange.text+closeTag;
}
}
else if(MOZ)
{
// fint the length of the selected text
var txtLength = parseInt(txtAr.textLength);
// find the start position
var selStart = txtAr.selectionStart;
// find the end position
var selEnd = txtAr.selectionEnd;
if (selEnd == 2 || selEnd == 1)
{
selEnd = txtLength;
}
// text before the selected text
var sect1 = (txtAr.value).substring(0,selStart);
// the selected text
var sect2 = (txtAr.value).substring(selStart,selEnd);
// text after the selected text
var sect3 = (txtAr.value).substring(selEnd,txtLength);
// add the tags before and after the selected text
txtAr.value = sect1 + openTag+sect2 + closeTag+sect3;
txtAr.focus();
}
else
document.getElementById(textAreaId+"").value+=tag;
}
תרמו לדף זה: ניר טייב ואחרים.

