Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 11

Discussione: HtmlArea

  1. #1

    HtmlArea

    Premeto che di JS ne so poco e NIENTE, quindi il compito sarà arduo.
    Ho scaricato HtmlArea e sto cercando di personalizzarlo e "itanializzarlo", in parte qualcosa ho fatto, ma ora sorgono i problemi.
    Posterò il codice in più volte dato che è lunghetto.

  2. #2
    editor.js (parte I)

    codice:
    document.write('<style type="text/css">\n');
    document.write('.btn     { width: 22px; height: 22px; border: 1px solid buttonface; margin: 0; padding: 0; }\n');
    document.write('.btnOver { width: 22px; height: 22px; border: 1px outset; }\n');
    document.write('.btnDown { width: 22px; height: 22px; border: 1px inset; background-color: buttonhighlight; }\n');
    document.write('.btnNA   { width: 22px; height: 22px; border: 1px solid buttonface; filter: alpha(opacity=25); }\n');
    document.write('.cMenu     { background-color: threedface; color: menutext; cursor: Default; font-family: MS Sans Serif; font-size: 8pt; padding: 2 12 2 16; }');
    document.write('.cMenuOver { background-color: highlight; color: highlighttext; cursor: Default; font-family: MS Sans Serif; font-size: 8pt; padding: 2 12 2 16; }');
    document.write('.cMenuDivOuter { background-color: threedface; height: 9 }');
    document.write('.cMenuDivInner { margin: 0 4 0 4; border-width: 1; border-style: solid; border-color: threedshadow threedhighlight threedhighlight threedshadow; }');
    document.write('</style>\n');
    
    function editor_defaultConfig(objname) {
    
    this.version = "2.03"
    
    this.width =  "auto";
    this.height = "auto";
    this.bodyStyle = 'background-color: #FFFFFF; font-family: "Verdana"; font-size: x-small;';
    this.imgURL = _editor_url + 'images/';
    this.debug  = 0;
    
    this.replaceNextlines = 0;
    this.plaintextInput = 0;
    
    this.toolbar = [
    
        ['bold','italic','underline','separator'],
        ['justifyleft','justifycenter','justifyright','separator'],
        ['OrderedList','UnOrderedList','Outdent','Indent','separator'],
        ['forecolor','backcolor','separator'],
        ['HorizontalRule','Createlink','InsertImage','InsertTable','htmlmode','separator'],
        ['popupeditor','about']];
    
    this.fontstyles = [
    ];
    
    this.btnList = {            
        "bold":           ['Bold',                 'Grassetto',               'editor_action(this.id)',  'ed_format_bold.gif'],
        "italic":         ['Italic',               'Corsivo',             'editor_action(this.id)',  'ed_format_italic.gif'],
        "underline":      ['Underline',            'Sottolineato',          'editor_action(this.id)',  'ed_format_underline.gif'],
        "strikethrough":  ['StrikeThrough',        'Strikethrough',      'editor_action(this.id)',  'ed_format_strike.gif'],
        "subscript":      ['SubScript',            'Subscript',          'editor_action(this.id)',  'ed_format_sub.gif'],
        "superscript":    ['SuperScript',          'Superscript',        'editor_action(this.id)',  'ed_format_sup.gif'],
        "justifyleft":    ['JustifyLeft',          'Allinea a sinistra',       'editor_action(this.id)',  'ed_align_left.gif'],
        "justifycenter":  ['JustifyCenter',        'Allinea al centro',     'editor_action(this.id)',  'ed_align_center.gif'],
        "justifyright":   ['JustifyRight',         'Allinea a destra',      'editor_action(this.id)',  'ed_align_right.gif'],
    	    "justifyjustify":   ['JustifyJustify',         'Giustifica',      'editor_action(this.id)',  'ed_align_justify.gif'],
        "orderedlist":    ['InsertOrderedList',    'Elenco numerico',       'editor_action(this.id)',  'ed_list_num.gif'],
        "unorderedlist":  ['InsertUnorderedList',  'Elenco puntato',      'editor_action(this.id)',  'ed_list_bullet.gif'],
        "outdent":        ['Outdent',              'Decrease Indent',    'editor_action(this.id)',  'ed_indent_less.gif'],
        "indent":         ['Indent',               'Increase Indent',    'editor_action(this.id)',  'ed_indent_more.gif'],
        "forecolor":      ['ForeColor',            'Colore testo',         'editor_action(this.id)',  'ed_color_fg.gif'],
        "backcolor":      ['BackColor',            'Background Color',   'editor_action(this.id)',  'ed_color_bg.gif'],
        "horizontalrule": ['InsertHorizontalRule', 'Horizontal Rule',    'editor_action(this.id)',  'ed_hr.gif'],
        "createlink":     ['CreateLink',           'Collegamento ipertestuale',    'editor_action(this.id)',  'ed_link.gif'],
        "insertimage":    ['InsertImage',          'Insert Image',       'editor_action(this.id)',  'ed_image.gif'],
        "inserttable":    ['InsertTable',          'Inserisci una tabella',       'editor_action(this.id)',  'insert_table.gif'],
        "htmlmode":       ['HtmlMode',             'Mostra il codice HTML',   'editor_setmode(\''+objname+'\')', 'ed_html.gif'],
        "popupeditor":    ['popupeditor',          'Enlarge Editor',     'editor_action(this.id)',  'fullscreen_maximize.gif'],
        "about":          ['about',                'About this editor',  'editor_about(\''+objname+'\')',  'ed_about.gif'],
    
        "custom1":           ['custom1',         'Purpose of button 1',  'editor_action(this.id)',  'ed_custom.gif'],
        "custom2":           ['custom2',         'Purpose of button 2',  'editor_action(this.id)',  'ed_custom.gif'],
        "custom3":           ['custom3',         'Purpose of button 3',  'editor_action(this.id)',  'ed_custom.gif'],
    
        "help":           ['showhelp',             'Help using editor',  'editor_action(this.id)',  'ed_help.gif']};
    
    
    }
    
    
    function editor_generate(objname,userConfig) {
    
      var config = new editor_defaultConfig(objname);
      if (userConfig) { 
        for (var thisName in userConfig) {
          if (userConfig[thisName]) { config[thisName] = userConfig[thisName]; }
        }
      }
      document.all[objname].config = config;
    
      var obj    = document.all[objname];
      if (!config.width || config.width == "auto") {
        if      (obj.style.width) { config.width = obj.style.width; }
        else if (obj.cols)        { config.width = (obj.cols * 8) + 22; }
        else                      { config.width = '100%'; }
      }
      if (!config.height || config.height == "auto") {
        if      (obj.style.height) { config.height = obj.style.height; }
        else if (obj.rows)         { config.height = obj.rows * 17 }
        else                       { config.height = '200'; }
      }
    
      var tblOpen  = '<table border=0 cellspacing=0 cellpadding=0 style="float: left;"  unselectable="on"><tr><td style="border: none; padding: 1 0 0 0"><nobr>';
      var tblClose = '</nobr></td></tr></table>\n';
    
      var toolbar = '';
      var btnGroup, btnItem, aboutEditor;
      for (var btnGroup in config.toolbar) {
    
        if (config.toolbar[btnGroup].length == 1 &&
            config.toolbar[btnGroup][0].toLowerCase() == "linebreak") {
          toolbar += '<br clear="all">';
          continue;
        }
    
        toolbar += tblOpen;
        for (var btnItem in config.toolbar[btnGroup]) {
          var btnName = config.toolbar[btnGroup][btnItem].toLowerCase();
    
          if (btnName == "fontname") {
            toolbar += '<select id="_' +objname+ '_FontName" onChange="editor_action(this.id)" unselectable="on" style="margin: 1 2 0 2; font-size: 12px;">';
            for (var fontname in config.fontnames) {
              toolbar += '<option value="' +config.fontnames[fontname]+ '">' +fontname+ '</option>'
            }
            toolbar += '</select>';
            continue;
          }
    
          if (btnName == "fontsize") {
            toolbar += '<select id="_' +objname+ '_FontSize" onChange="editor_action(this.id)" unselectable="on" style="margin: 1 2 0 0; font-size: 12px;">';
            for (var fontsize in config.fontsizes) {
              toolbar += '<option value="' +config.fontsizes[fontsize]+ '">' +fontsize+ '</option>'
            }
            toolbar += '</select>\n';
            continue;
          }
    
          if (btnName == "fontstyle") {
            toolbar += '<select id="_' +objname+ '_FontStyle" onChange="editor_action(this.id)" unselectable="on" style="margin: 1 2 0 0; font-size: 12px;">';
            + '<option value="">Font Style</option>';
            for (var i in config.fontstyles) {
              var fontstyle = config.fontstyles[i];
              toolbar += '<option value="' +fontstyle.className+ '">' +fontstyle.name+ '</option>'
            }
            toolbar += '</select>';
            continue;
          }
    
          if (btnName == "separator") {
            toolbar += '<span style="border: 1px inset; width: 1px; font-size: 16px; height: 16px; margin: 0 3 0 3"></span>';
            continue;
          }
    
          var btnObj = config.btnList[btnName];
          if (btnName == 'linebreak') { alert("htmlArea error: 'linebreak' must be in a subgroup by itself, not with other buttons.\n\nhtmlArea wysiwyg editor not created."); return; }
          if (!btnObj) { alert("htmlArea error: button '" +btnName+ "' not found in button list when creating the wysiwyg editor for '"+objname+"'.\nPlease make sure you entered the button name correctly.\n\nhtmlArea wysiwyg editor not created."); return; }
          var btnCmdID   = btnObj[0];
          var btnTitle   = btnObj[1];
          var btnOnClick = btnObj[2];
          var btnImage   = btnObj[3];
          toolbar += '<button title="' +btnTitle+ '" id="_' +objname+ '_' +btnCmdID+ '" class="btn" onClick="' +btnOnClick+ '" onmouseover="if(this.className==\'btn\'){this.className=\'btnOver\'}" onmouseout="if(this.className==\'btnOver\'){this.className=\'btn\'}" unselectable="on">[img]' +config.imgURL + btnImage+ '[/img]</button>';
    
    
        }
        toolbar += tblClose;
      }
    
      var editor = '<span id="_editor_toolbar"><table border=0 cellspacing=0 cellpadding=0 bgcolor="buttonface" style="padding: 1 0 0 2" width=' + config.width + ' unselectable="on"><tr><td>\n'
      + toolbar
      + '</td></tr></table>\n'
      + '</td></tr></table></span>\n'
      + '<textarea ID="_' +objname + '_editor" style="width:' +config.width+ '; height:' +config.height+ '; margin-top: -1px; margin-bottom: -1px;" wrap=soft></textarea>';
    
      editor += '<div id="_' +objname + '_cMenu" style="position: absolute; visibility: hidden;"></div>';
    
      if (!config.debug) { document.all[objname].style.display = "none"; }
    
      if (config.plaintextInput) {
        var contents = document.all[objname].value;
        contents = contents.replace(/\r\n/g, '
    ');
        contents = contents.replace(/\n/g, '
    ');
        contents = contents.replace(/\r/g, '
    ');
        document.all[objname].value = contents;
      }
    
      document.all[objname].insertAdjacentHTML('afterEnd', editor)
    
      editor_setmode(objname, 'init');
    
      for (var idx=0; idx < document.forms.length; idx++) {
        var r = document.forms[idx].attachEvent('onsubmit', function() { editor_filterOutput(objname); });
        if (!r) { alert("Error attaching event to form!"); }
      }
    
    return true;
    
    }
    
    
    function editor_action(button_id) {
    
      var BtnParts = Array();
      BtnParts = button_id.split("_");
      var objname    = button_id.replace(/^_(.*)_[^_]*$/, '$1');
      var cmdID      = BtnParts[ BtnParts.length-1 ];
      var button_obj = document.all[button_id];
      var editor_obj = document.all["_" +objname + "_editor"];
      var config     = document.all[objname].config;
    
      if (cmdID == 'showhelp') {
        window.open(_editor_url + "popups/editor_help.html", 'EditorHelp');
        return;
      }
    
      if (cmdID == 'popupeditor') {
        window.open(_editor_url + "popups/fullscreen.html?"+objname,
                    'FullScreen',
                    'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=640,height=480');
        return;
      }

  3. #3
    editor.js (parte II)

    codice:
      if (editor_obj.tagName.toLowerCase() == 'textarea') { return; }
    
      var editdoc = editor_obj.contentWindow.document;
      editor_focus(editor_obj);
    
      var idx = button_obj.selectedIndex;
      var val = (idx != null) ? button_obj[ idx ].value : null;
    
      if (0) {} 
    
      else if (cmdID == 'custom1') {
        alert("Hello, I am custom button 1!");
      }
    
    
      else if (cmdID == 'custom2') {
        var myTitle = "This is a custom title";
        var myText = showModalDialog(_editor_url + "popups/custom2.html",
                                     myTitle,
                                     "resizable: yes; help: no; status: no; scroll: no; ");
        if (myText) { editor_insertHTML(objname, myText); }
      }
    
      else if (cmdID == 'custom3') {
        editor_insertHTML(objname, "It's easy to add buttons that insert text!");
      }
    
      else if (cmdID == 'FontName' && val) {
        editdoc.execCommand(cmdID,0,val);
      }
    
      else if (cmdID == 'FontSize' && val) {
        editdoc.execCommand(cmdID,0,val);
      }
    
      else if (cmdID == 'FontStyle' && val) {
        editdoc.execCommand('RemoveFormat');
        editdoc.execCommand('FontName',0,'636c6173734e616d6520706c616365686f6c646572');
        var fontArray = editdoc.all.tags("FONT");
        for (i=0; i<fontArray.length; i++) {
          if (fontArray[i].face == '636c6173734e616d6520706c616365686f6c646572') {
            fontArray[i].face = "";
            fontArray[i].className = val;
            fontArray[i].outerHTML = fontArray[i].outerHTML.replace(/face=['"]+/, "");
            }
        }
        button_obj.selectedIndex =0;
      }
    
      else if (cmdID == 'ForeColor' || cmdID == 'BackColor') {
        var oldcolor = _dec_to_rgb(editdoc.queryCommandValue(cmdID));
        var newcolor = showModalDialog(_editor_url + "popups/select_color.html", oldcolor, "resizable: no; help: no; status: no; scroll: no;");
        if (newcolor != null) { editdoc.execCommand(cmdID, false, "#"+newcolor); }
      }
    
      else {
      
        if (cmdID.toLowerCase() == 'subscript' && editdoc.queryCommandState('superscript')) { editdoc.execCommand('superscript'); }
        if (cmdID.toLowerCase() == 'superscript' && editdoc.queryCommandState('subscript')) { editdoc.execCommand('subscript'); }
    
        if (cmdID.toLowerCase() == 'createlink'){
          editdoc.execCommand(cmdID,1);
        }
    
        else if (cmdID.toLowerCase() == 'insertimage'){
          showModalDialog(_editor_url + "popups/insert_image.html", editdoc, "resizable: no; help: no; status: no; scroll: no; ");
        }
    
        else if (cmdID.toLowerCase() == 'inserttable'){
          showModalDialog(_editor_url + "popups/insert_table.html?"+objname,
                                     window,
                                     "resizable: yes; help: no; status: no; scroll: no; ");
        }
    
        else { editdoc.execCommand(cmdID); }
      }
    
      editor_event(objname);
    }
    
    
    function editor_event(objname,runDelay) {
      var config = document.all[objname].config;
      var editor_obj  = document.all["_" +objname+  "_editor"];
      if (runDelay == null) { runDelay = 0; }
      var editdoc;
      var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;
    
        if (editEvent && editEvent.keyCode) {
          var ord       = editEvent.keyCode;
          var ctrlKey   = editEvent.ctrlKey;
          var altKey    = editEvent.altKey;
          var shiftKey  = editEvent.shiftKey;
    
          if (ord == 16) { return; }
          if (ord == 17) { return; }
          if (ord == 18) { return; }
    
    
          if (ctrlKey && (ord == 122 || ord == 90)) {
    	  
            return;
          }
          if ((ctrlKey && (ord == 121 || ord == 89)) ||
              ctrlKey && shiftKey && (ord == 122 || ord == 90)) {
            return;
          }
        }
    
    
      if (runDelay > 0) { return setTimeout(function(){ editor_event(objname); }, runDelay); }
    
      if (this.tooSoon == 1 && runDelay >= 0) { this.queue = 1; return; }
      this.tooSoon = 1;
      setTimeout(function(){
        this.tooSoon = 0;
        if (this.queue) { editor_event(objname,-1); };
        this.queue = 0;
        }, 333);
    
    
      editor_updateOutput(objname);
      editor_updateToolbar(objname);
    
    }
    
    function editor_updateToolbar(objname,action) {
      var config = document.all[objname].config;
      var editor_obj  = document.all["_" +objname+  "_editor"];
    
    
      if (action == "enable" || action == "disable") {
        var tbItems = new Array('FontName','FontSize','FontStyle');
        for (var btnName in config.btnList) { tbItems.push(config.btnList[btnName][0]); }
    
        for (var idxN in tbItems) {
          var cmdID = tbItems[idxN].toLowerCase();
          var tbObj = document.all["_" +objname+ "_" +tbItems[idxN]];
          if (cmdID == "htmlmode" || cmdID == "about" || cmdID == "showhelp" || cmdID == "popupeditor") { continue; }
          if (tbObj == null) { continue; }
          var isBtn = (tbObj.tagName.toLowerCase() == "button") ? true : false;
    
          if (action == "enable")  { tbObj.disabled = false; if (isBtn) { tbObj.className = 'btn' }}
          if (action == "disable") { tbObj.disabled = true;  if (isBtn) { tbObj.className = 'btnNA' }}
        }
        return;
      }
    
    
      if (editor_obj.tagName.toLowerCase() == 'textarea') { return; } mode
      var editdoc = editor_obj.contentWindow.document;
    
      var fontname_obj = document.all["_" +objname+ "_FontName"];
      if (fontname_obj) {
        var fontname = editdoc.queryCommandValue('FontName');
        if (fontname == null) { fontname_obj.value = null; }
        else {
          var found = 0;
          for (i=0; i<fontname_obj.length; i++) {
            if (fontname.toLowerCase() == fontname_obj[i].text.toLowerCase()) {
              fontname_obj.selectedIndex = i;
              found = 1;
            }
          }
          if (found != 1) { fontname_obj.value = null; }
        }
      }
    
      var fontsize_obj = document.all["_" +objname+ "_FontSize"];
      if (fontsize_obj) {
        var fontsize = editdoc.queryCommandValue('FontSize');
        if (fontsize == null) { fontsize_obj.value = null; }
        else {
          var found = 0;
          for (i=0; i<fontsize_obj.length; i++) {
            if (fontsize == fontsize_obj[i].value) { fontsize_obj.selectedIndex = i; found=1; }
          }
          if (found != 1) { fontsize_obj.value = null; }
        }
      }
    
      var classname_obj = document.all["_" +objname+ "_FontStyle"];
      if (classname_obj) {
        var curRange = editdoc.selection.createRange();
    
        var pElement;
        if (curRange.length) { pElement = curRange[0]; }
        else                 { pElement = curRange.parentElement(); }
        while (pElement && !pElement.className) { pElement = pElement.parentElement; }
    
        var thisClass = pElement ? pElement.className.toLowerCase() : "";
        if (!thisClass && classname_obj.value) { classname_obj.value = null; }
        else {
          var found = 0;
          for (i=0; i<classname_obj.length; i++) {
            if (thisClass == classname_obj[i].value.toLowerCase()) {
              classname_obj.selectedIndex = i;
              found=1;
            }
          }
          if (found != 1) { classname_obj.value = null; }
        }
      }
    
      var IDList = Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyRight','InsertOrderedList','InsertUnorderedList');
      for (i=0; i<IDList.length; i++) {
        var btnObj = document.all["_" +objname+ "_" +IDList[i]];
        if (btnObj == null) { continue; }
        var cmdActive = editdoc.queryCommandState( IDList[i] );
    
        if (!cmdActive)  {
          if (btnObj.className != 'btn') { btnObj.className = 'btn'; }
          if (btnObj.disabled  != false) { btnObj.disabled = false; }
        } else if (cmdActive)  {
          if (btnObj.className != 'btnDown') { btnObj.className = 'btnDown'; }
          if (btnObj.disabled  != false)   { btnObj.disabled = false; }
        }
      }
    }
    
    
    function editor_updateOutput(objname) {
      var config     = document.all[objname].config;
      var editor_obj  = document.all["_" +objname+  "_editor"];
      var editEvent = editor_obj.contentWindow ? editor_obj.contentWindow.event : event;
      var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');
      var editdoc = isTextarea ? null : editor_obj.contentWindow.document;
    
      var contents;
      if (isTextarea) { contents = editor_obj.value; }
      else            { contents = editdoc.body.innerHTML; }
    
      if (config.lastUpdateOutput && config.lastUpdateOutput == contents) { return; }
      else { config.lastUpdateOutput = contents; }
    
      document.all[objname].value = contents;
    
    }
    
    
    function editor_filterOutput(objname) {
      editor_updateOutput(objname);
      var contents = document.all[objname].value;
      var config   = document.all[objname].config;
    
      if (contents.toLowerCase() == '
    
    </p>') { contents = ""; }
    
      var filterTag = function(tagBody,tagName,tagAttr) {
        tagName = tagName.toLowerCase();
        var closingTag = (tagBody.match(/^<\//)) ? true : false;
    
        if (tagName == 'img') { tagBody = tagBody.replace(/(src\s*=\s*.)[^*]*(\*\*\*)/, "$1$2"); }
        if (tagName == 'a')   { tagBody = tagBody.replace(/(href\s*=\s*.)[^*]*(\*\*\*)/, "$1$2"); }
    
        return tagBody;
      };
    
      RegExp.lastIndex = 0;
        var matchTag = /<\/?(\w+)((?:[^'">]*|'[^']*'|"[^"]*")*)>/g;
    
      contents = contents.replace(matchTag, filterTag);
    
      if (config.replaceNextlines) { 
        contents = contents.replace(/\r\n/g, ' ');
        contents = contents.replace(/\n/g, ' ');
        contents = contents.replace(/\r/g, ' ');
      }
    
    
      document.all[objname].value = contents;
    
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_setmode
      Description : change mode between WYSIWYG and HTML editor
      Usage       : editor_setmode(objname, mode);
      Arguments   : objname - button id string with editor and action name
                    mode      - init, textedit, or wysiwyg
    \* ---------------------------------------------------------------------- */
    
    function editor_setmode(objname, mode) {
      var config     = document.all[objname].config;
      var editor_obj = document.all["_" +objname + "_editor"];
    
      // wait until document is fully loaded
      if (document.readyState != 'complete') {
        setTimeout(function() { editor_setmode(objname,mode) }, 25);
        return;
      }
    
      // define different editors
      var TextEdit   = '<textarea ID="_' +objname + '_editor" style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ '; margin-top: -1px; margin-bottom: -1px;"></textarea>';
      var RichEdit   = '<iframe ID="_' +objname+ '_editor"    style="width:' +editor_obj.style.width+ '; height:' +editor_obj.style.height+ ';"></iframe>';
    
     // src="' +_editor_url+ 'popups/blank.html"
    
      //
      // Switch to TEXTEDIT mode
      //
    
      if (mode == "textedit" || editor_obj.tagName.toLowerCase() == 'iframe') {
        config.mode = "textedit";
        var editdoc = editor_obj.contentWindow.document;
        var contents = editdoc.body.createTextRange().htmlText;
        editor_obj.outerHTML = TextEdit;
        editor_obj = document.all["_" +objname + "_editor"];
        editor_obj.value = contents;
        editor_event(objname);
    
        editor_updateToolbar(objname, "disable");  // disable toolbar items
    
        // set event handlers
        editor_obj.onkeydown   = function() { editor_event(objname); }
        editor_obj.onkeypress  = function() { editor_event(objname); }
        editor_obj.onkeyup     = function() { editor_event(objname); }
        editor_obj.onmouseup   = function() { editor_event(objname); }
        editor_obj.ondrop      = function() { editor_event(objname, 100); }     // these events fire before they occur
        editor_obj.oncut       = function() { editor_event(objname, 100); }
        editor_obj.onpaste     = function() { editor_event(objname, 100); }
        editor_obj.onblur      = function() { editor_event(objname, -1); }
    
        editor_updateOutput(objname);
        editor_focus(editor_obj);
      }
    
      //
      // Switch to WYSIWYG mode
      //
    
      else {
        config.mode = "wysiwyg";
        var contents = editor_obj.value;
        if (mode == 'init') { contents = document.all[objname].value; } // on init use original textarea content
    
        // create editor
        editor_obj.outerHTML = RichEdit;
        editor_obj = document.all["_" +objname + "_editor"];
    
        // get iframe document object
    
        // create editor contents (and default styles for editor)
        var html = "";
        html += '<html><head>\n';
        if (config.stylesheet) {
          html += '<link href="' +config.stylesheet+ '" rel="stylesheet" type="text/css">\n';
        }
        html += '<style>\n';
        html += 'body {' +config.bodyStyle+ '} \n';
        for (var i in config.fontstyles) {
          var fontstyle = config.fontstyles[i];
          if (fontstyle.classStyle) {
            html += '.' +fontstyle.className+ ' {' +fontstyle.classStyle+ '}\n';
          }
        }
        html += '</style>\n'
          + '</head>\n'
          + '<body contenteditable="true" topmargin=1 leftmargin=1'

  4. #4
    editor.js (parte III)

    codice:
    // still working on this
    //      + ' oncontextmenu="parent.editor_cMenu_generate(window,\'' +objname+ '\');"'
          +'>'
          + contents
          + '</body>\n'
          + '</html>\n';
    
        // write to editor window
        var editdoc = editor_obj.contentWindow.document;
    
        editdoc.open();
        editdoc.write(html);
        editdoc.close();
    
        editor_updateToolbar(objname, "enable");  // enable toolbar items
    
        // store objname under editdoc
        editdoc.objname = objname;
    
        // set event handlers
        editdoc.onkeydown      = function() { editor_event(objname); }
        editdoc.onkeypress     = function() { editor_event(objname); }
        editdoc.onkeyup        = function() { editor_event(objname); }
        editdoc.onmouseup      = function() { editor_event(objname); }
        editdoc.body.ondrop    = function() { editor_event(objname, 100); }     // these events fire before they occur
        editdoc.body.oncut     = function() { editor_event(objname, 100); }
        editdoc.body.onpaste   = function() { editor_event(objname, 100); }
        editdoc.body.onblur    = function() { editor_event(objname, -1); }
    
        // bring focus to editor
        if (mode != 'init') {             // don't focus on page load, only on mode switch
          editor_focus(editor_obj);
        }
    
      }
    
      // Call update UI
      if (mode != 'init') {             // don't update UI on page load, only on mode switch
        editor_event(objname);
      }
    
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_focus
      Description : bring focus to the editor
      Usage       : editor_focus(editor_obj);
      Arguments   : editor_obj - editor object
    \* ---------------------------------------------------------------------- */
    
    function editor_focus(editor_obj) {
    
      // check editor mode
      if (editor_obj.tagName.toLowerCase() == 'textarea') {         // textarea
        var myfunc = function() { editor_obj.focus(); };
        setTimeout(myfunc,100);                                     // doesn't work all the time without delay
      }
    
      else {                                                        // wysiwyg
        var editdoc = editor_obj.contentWindow.document;            // get iframe editor document object
        var editorRange = editdoc.body.createTextRange();           // editor range
        var curRange    = editdoc.selection.createRange();          // selection range
    
        if (curRange.length == null &&                              // make sure it's not a controlRange
            !editorRange.inRange(curRange)) {                       // is selection in editor range
          editorRange.collapse();                                   // move to start of range
          editorRange.select();                                     // select
          curRange = editorRange;
        }
      }
    
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_about
      Description : display "about this editor" popup
    \* ---------------------------------------------------------------------- */
    
    function editor_about(objname) {
      showModalDialog(_editor_url + "popups/about.html", window, "resizable: yes; help: no; status: no; scroll: no; ");
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : _dec_to_rgb
      Description : convert dec color value to rgb hex
      Usage       : var hex = _dec_to_rgb('65535');   // returns FFFF00
      Arguments   : value   - dec value
    \* ---------------------------------------------------------------------- */
    
    function _dec_to_rgb(value) {
      var hex_string = "";
      for (var hexpair = 0; hexpair < 3; hexpair++) {
        var myByte = value & 0xFF;            // get low byte
        value >>= 8;                        // drop low byte
        var nybble2 = myByte & 0x0F;          // get low nybble (4 bits)
        var nybble1 = (myByte >> 4) & 0x0F;   // get high nybble
        hex_string += nybble1.toString(16); // convert nybble to hex
        hex_string += nybble2.toString(16); // convert nybble to hex
      }
      return hex_string.toUpperCase();
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_insertHTML
      Description : insert string at current cursor position in editor.  If
                    two strings are specifed, surround selected text with them.
      Usage       : editor_insertHTML(objname, str1, [str2], reqSelection)
      Arguments   : objname - ID of textarea
                    str1 - HTML or text to insert
                    str2 - HTML or text to insert (optional argument)
                    reqSelection - (1 or 0) give error if no text selected
    \* ---------------------------------------------------------------------- */
    
    function editor_insertHTML(objname, str1,str2, reqSel) {
      var config     = document.all[objname].config;
      var editor_obj = document.all["_" +objname + "_editor"];    // editor object
      if (str1 == null) { str1 = ''; }
      if (str2 == null) { str2 = ''; }
    
      // for non-wysiwyg capable browsers just add to end of textbox
      if (document.all[objname] && editor_obj == null) {
        document.all[objname].focus();
        document.all[objname].value = document.all[objname].value + str1 + str2;
        return;
      }
    
      // error checking
      if (editor_obj == null) { return alert("Unable to insert HTML.  Invalid object name '" +objname+ "'."); }
    
      editor_focus(editor_obj);
    
      var tagname = editor_obj.tagName.toLowerCase();
      var sRange;
    
     // insertHTML for wysiwyg iframe
      if (tagname == 'iframe') {
        var editdoc = editor_obj.contentWindow.document;
        sRange  = editdoc.selection.createRange();
        var sHtml   = sRange.htmlText;
    
        // check for control ranges
        if (sRange.length) { return alert("Unable to insert HTML.  Try highlighting content instead of selecting it."); }
    
        // insert HTML
        var oldHandler = window.onerror;
        window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; } // partial table selections cause errors
        if (sHtml.length) {                                 // if content selected
          if (str2) { sRange.pasteHTML(str1 +sHtml+ str2) } // surround
          else      { sRange.pasteHTML(str1); }             // overwrite
        } else {                                            // if insertion point only
          if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
          sRange.pasteHTML(str1 + str2);                    // insert strings
        }
        window.onerror = oldHandler;
      }
    
      // insertHTML for plaintext textarea
      else if (tagname == 'textarea') {
        editor_obj.focus();
        sRange  = document.selection.createRange();
        var sText   = sRange.text;
    
        // insert HTML
        if (sText.length) {                                 // if content selected
          if (str2) { sRange.text = str1 +sText+ str2; }  // surround
          else      { sRange.text = str1; }               // overwrite
        } else {                                            // if insertion point only
          if (reqSel) { return alert("Unable to insert HTML.  You must select something first."); }
          sRange.text = str1 + str2;                        // insert strings
        }
      }
      else { alert("Unable to insert HTML.  Unknown object tag type '" +tagname+ "'."); }
    
      // move to end of new content
      sRange.collapse(false); // move to end of range
      sRange.select();        // re-select
    
    }

  5. #5
    editor.js (parte IV)

    codice:
    /* ---------------------------------------------------------------------- *\
      Function    : editor_getHTML
      Description : return HTML contents of editor (in either wywisyg or html mode)
      Usage       : var myHTML = editor_getHTML('objname');
    \* ---------------------------------------------------------------------- */
    
    function editor_getHTML(objname) {
      var editor_obj = document.all["_" +objname + "_editor"];
      var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');
    
      if (isTextarea) { return editor_obj.value; }
      else            { return editor_obj.contentWindow.document.body.innerHTML; }
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_setHTML
      Description : set HTML contents of editor (in either wywisyg or html mode)
      Usage       : editor_setHTML('objname',"html <u>here</u>");
    \* ---------------------------------------------------------------------- */
    
    function editor_setHTML(objname, html) {
      var editor_obj = document.all["_" +objname + "_editor"];
      var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');
    
      if (isTextarea) { editor_obj.value = html; }
      else            { editor_obj.contentWindow.document.body.innerHTML = html; }
    }
    
    /* ---------------------------------------------------------------------- *\
      Function    : editor_appendHTML
      Description : append HTML contents to editor (in either wywisyg or html mode)
      Usage       : editor_appendHTML('objname',"html <u>here</u>");
    \* ---------------------------------------------------------------------- */
    
    function editor_appendHTML(objname, html) {
      var editor_obj = document.all["_" +objname + "_editor"];
      var isTextarea = (editor_obj.tagName.toLowerCase() == 'textarea');
    
      if (isTextarea) { editor_obj.value += html; }
      else            { editor_obj.contentWindow.document.body.innerHTML += html; }
    }
    
    /* ---------------------------------------------------------------- */
    
    function _isMouseOver(obj,event) {       // determine if mouse is over object
      var mouseX    = event.clientX;
      var mouseY    = event.clientY;
    
      var objTop    = obj.offsetTop;
      var objBottom = obj.offsetTop + obj.offsetHeight;
      var objLeft   = obj.offsetLeft;
      var objRight  = obj.offsetLeft + obj.offsetWidth;
    
      if (mouseX >= objLeft && mouseX <= objRight &&
          mouseY >= objTop  && mouseY <= objBottom) { return true; }
    
      return false;
    }
    
    /* ---------------------------------------------------------------- */
    
    function editor_cMenu_generate(editorWin,objname) {
      var parentWin = window;
      editorWin.event.returnValue = false;  // cancel default context menu
    
      // define content menu options
      var cMenuOptions = [ // menu name, shortcut displayed, javascript code
        ['Cut', 'Ctrl-X', function() {}],
        ['Copy', 'Ctrl-C', function() {}],
        ['Paste', 'Ctrl-C', function() {}],
        ['Delete', 'DEL', function() {}],
        ['---', null, null],
        ['Select All', 'Ctrl-A', function() {}],
        ['Clear All', '', function() {}],
        ['---', null, null],
        ['About this editor...', '', function() {
          alert("about this editor");
        }]];
        editor_cMenu.options = cMenuOptions; // save options
    
      // generate context menu
      var cMenuHeader = ''
        + '<div id="_'+objname+'_cMenu" onblur="editor_cMenu(this);" oncontextmenu="return false;" onselectstart="return false"'
        + '  style="position: absolute; visibility: hidden; cursor: default; width: 167px; background-color: threedface;'
        + '         border: solid 1px; border-color: threedlightshadow threeddarkshadow threeddarkshadow threedlightshadow;">'
        + '<table border=0 cellspacing=0 cellpadding=0 width="100%" style="width: 167px; background-color: threedface; border: solid 1px; border-color: threedhighlight threedshadow threedshadow threedhighlight;">'
        + ' <tr><td colspan=2 height=1></td></tr>';
    
      var cMenuList = '';
    
      var cMenuFooter = ''
        + ' <tr><td colspan=2 height=1></td></tr>'
        + '</table></div>';
    
      for (var menuIdx in editor_cMenu.options) {
        var menuName = editor_cMenu.options[menuIdx][0];
        var menuKey  = editor_cMenu.options[menuIdx][1];
        var menuCode = editor_cMenu.options[menuIdx][2];
    
        // separator
        if (menuName == "---" || menuName == "separator") {
          cMenuList += ' <tr><td colspan=2 class="cMenuDivOuter"><div class="cMenuDivInner"></div></td></tr>';
        }
    
        // menu option
        else {
          cMenuList += '<tr class="cMenu" onMouseOver="editor_cMenu(this)" onMouseOut="editor_cMenu(this)" onClick="editor_cMenu(this, \'' +menuIdx+ '\',\'' +objname+ '\')">';
          if (menuKey) { cMenuList += ' <td align=left class="cMenu">' +menuName+ '</td><td align=right class="cMenu">' +menuKey+ '</td>'; }
          else         { cMenuList += ' <td colspan=2 class="cMenu">' +menuName+ '</td>'; }
          cMenuList += '</tr>';
        }
      }
    
      var cMenuHTML = cMenuHeader + cMenuList + cMenuFooter;
    
    
      document.all['_'+objname+'_cMenu'].outerHTML = cMenuHTML;
    
      editor_cMenu_setPosition(parentWin, editorWin, objname);
    
      parentWin['_'+objname+'_cMenu'].style.visibility = 'visible';
      parentWin['_'+objname+'_cMenu'].focus();
    
    }
    
    /* ---------------------------------------------------------------- */
    
    function editor_cMenu_setPosition(parentWin, editorWin, objname) {      // set object position that won't overlap window edge
      var event    = editorWin.event;
      var cMenuObj = parentWin['_'+objname+'_cMenu'];
      var mouseX   = event.clientX + parentWin.document.all['_'+objname+'_editor'].offsetLeft;
      var mouseY   = event.clientY + parentWin.document.all['_'+objname+'_editor'].offsetTop;
      var cMenuH   = cMenuObj.offsetHeight;
      var cMenuW   = cMenuObj.offsetWidth;
      var pageH    = document.body.clientHeight + document.body.scrollTop;
      var pageW    = document.body.clientWidth + document.body.scrollLeft;
    
      // set horzontal position
      if (mouseX + 5 + cMenuW > pageW) { var left = mouseX - cMenuW - 5; } // too far right
      else                            { var left = mouseX + 5; }
    
      // set vertical position
      if (mouseY + 5 + cMenuH > pageH) { var top = mouseY - cMenuH + 5; } // too far down
      else                            { var top = mouseY + 5; }
    
      cMenuObj.style.top = top;
      cMenuObj.style.left = left;
    
    }
    
    /* ---------------------------------------------------------------- */
    
    function editor_cMenu(obj,menuIdx,objname) {
      var action = event.type;
      if      (action == "mouseover" && !obj.disabled && obj.tagName.toLowerCase() == 'tr') {
        obj.className = 'cMenuOver';
        for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenuOver'; }
      }
      else if (action == "mouseout" && !obj.disabled && obj.tagName.toLowerCase() == 'tr')  {
        obj.className = 'cMenu';
        for (var i=0; i < obj.cells.length; i++) { obj.cells[i].className = 'cMenu'; }
      }
      else if (action == "click" && !obj.disabled) {
        document.all['_'+objname+'_cMenu'].style.visibility = "hidden";
        var menucode = editor_cMenu.options[menuIdx][2];
        menucode();
      }
      else if (action == "blur") {
        if (!_isMouseOver(obj,event)) { obj.style.visibility = 'hidden'; }
        else {
          if (obj.style.visibility != "hidden") { obj.focus(); }
        }
      }
      else { alert("editor_cMenu, unknown action: " + action); }
    }
    
    /* ---------------------------------------------------------------------- */

  6. #6
    Questa è la pagina che mosra l'editor (facciamo che si chiami form.htm)

    codice:
    <style type="text/css"><!--
      body, td  { font-family: arial; font-size: x-small; }
      a         { color: #0000BB; text-decoration: none; }
      a:hover   { color: #FF0000; text-decoration: underline; }
      .headline { font-family: arial black, arial; font-size: 28px; letter-spacing: -1px; }
      .headline2{ font-family: verdana, arial; font-size: 12px; }
      .subhead  { font-family: arial, arial; font-size: 18px; font-weight: bold; font-style: italic; }
      .backtotop     { font-family: arial, arial; font-size: xx-small;  }
      .code     { background-color: #EEEEEE; font-family: Courier New; font-size: x-small;
                  margin: 5px 0px 5px 0px; padding: 5px;
                  border: black 1px dotted;
                }
    
      font { font-family: arial black, arial; font-size: 28px; letter-spacing: -1px; }
    
    --></style>
    
    
    
    <script language="Javascript1.2">
    _editor_url = ""; 
    var win_ie_ver = parseFloat(navigator.appVersion.split("MSIE")[1]);
    if (navigator.userAgent.indexOf('Mac')        >= 0) { win_ie_ver = 0; }
    if (navigator.userAgent.indexOf('Windows CE') >= 0) { win_ie_ver = 0; }
    if (navigator.userAgent.indexOf('Opera')      >= 0) { win_ie_ver = 0; }
    if (win_ie_ver >= 5.5) {
      document.write('<scr' + 'ipt src="' +_editor_url+ 'editor.js"');
      document.write(' language="Javascript1.2"></scr' + 'ipt>');  
    } else { document.write('<scr'+'ipt>function editor_generate() { return false; }</scr'+'ipt>'); }
    </script>
    
    
    <form method=POST action="">
    
    
    <textarea name="yourFieldNameHere" style="width:800; height:150">
    
    </textarea>
    
    
    <script language="javascript1.2">
    editor_generate('yourFieldNameHere');
    </script>
    
    
    <script language="javascript1.2">
    var config = new Object();
    
    config.width = "90%";
    config.height = "200px";
    config.bodyStyle = 'background-color: white; font-family: "Verdana"; font-size: x-small;';
    config.debug = 0;
    
    config.toolbar = [
        ['bold','italic','underline','separator'],
        ['forecolor','backcolor','separator'],
    ];
    
    editor_generate('yourFieldNameHere2',config);
    </script>
    
    </form>

  7. #7
    Ok, ci siamo! Questo codice già è modificato. Ora vorrei togliere alcune righe da editor.js, ad esempio:

    codice:
    "outdent":        ['Outdent',              'Decrease Indent',    'editor_action(this.id)',  'ed_indent_less.gif'],
    ma form.htm mi dice:


    htmlArea error: button 'outdent' not found in button list when creating the wysiwyg editor for 'yourFieldNameHere'.
    Please make sure you entered the button name correctly.

    htmlArea wysiwyg editor not created.


    Si può risolvere?

  8. #8
    Utente di HTML.it L'avatar di Xinod
    Registrato dal
    Sep 2000
    Messaggi
    13,649
    la prossima volta lascia il link ad una paginetta funzionante...

    a me da errore la tua pagina form.htm, manca la textarea con name="yourFieldNameHere2" che però cerchi di inizializzare

    per risolvere definitivamente va studiato il codice in maniera molto approfondita
    cmq da l' errore che tu riporti quando tenti di inizializzare una textarea senza configurazione personalizzata,
    insomma se hai solo questo
    codice:
    <form method=POST action="">
    
    
    <textarea name="yourFieldNameHere" style="width:800; height:150">
    
    </textarea>
    
    
    <script language="javascript1.2">
    // editor_generate('yourFieldNameHere'); <-- è commentata!
    </script>
    
    
    <script language="javascript1.2">
    var config = new Object();
    
    config.width = "90%";
    config.height = "200px";
    config.bodyStyle = 'background-color: white; font-family: "Verdana"; font-size: x-small;';
    config.debug = 0;
    
    config.toolbar = [
        ['bold','italic','underline','separator'],
        ['forecolor','backcolor','separator'],
    ];
    
     editor_generate('yourFieldNameHere',config);
    </script>
    
    </form>
    puoi rimuovere nell' editor.js tutte le righe dei pulsanti che non intendi utilizzare senza che appaia l' errore
    ciao

  9. #9
    Il link funziona.
    Comunque ora provo e faccio sapere.

  10. #10
    Non riesco a capire dov'è l'errore, qui non si possono allegare file zippati vero? Se qualcuno vuole aiutarmi ci organiziamo per l'invio dei file, così si può lavorare mreglio.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.