简体   繁体   English

HTML JS文本编辑器

[英]HTML JS Text editor

i am trying to create a very simple html text editor. 我试图创建一个非常简单的html文本编辑器。 i have utilised the context menu function to have different format options once a user selects on the highlighted text on screen will have a span tag appended to it. 我已经利用上下文菜单功能为用户提供了不同的格式选项,一旦用户在屏幕上突出显示的文本上进行选择,将在其后附加一个span标签。

this is what i have. 这就是我所拥有的。

function StyleChange(property) {
    var span = document.createElement("span");
    span.style.color = property;

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

this works fine for changing the colour of the highlighted text. 这对于更改突出显示的文本的颜色效果很好。 what i would like to do is be able to use this function to change any format of style for the text by passing an extra parameter when the function is called. 我想做的是能够使用此函数通过在调用函数时传递一个额外的参数来更改文本样式的任何格式。 so when it is called it will say something like. 所以当它被调用时会说类似。 StyleChange('color',red) or StyleChange('background','yellow'). StyleChange('color',red)或StyleChange('background','yellow')。

something like 就像是

function StyleChange(style,property) {
    var span = document.createElement("span");
    **span.style. + style = property;**

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}

i get an error message with this any ideas? 我收到与此错误消息任何想法?

Square brackets are used to pass properties, like: 方括号用于传递属性,例如:

function StyleChange(property, value){
  var span = document.createElement('span');
  span.style[property] = value;
  if(window.getSelection){
    var sel = window.getSelection();
    if(sel.rangeCount){
      var range = sel.getRangeAt(0).cloneRange();
      range.surroundContents(span);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
}

You probably want 你可能想要

span.style += property;

instead. 代替。

Another consideration: you don't want to use the name property for your variable, since that's a reserved keyword (as you can see since it's highlighted in blue) and Bad Things™ will happen if you use one. 另一个注意事项:您不想为变量使用name property ,因为这是一个保留关键字(您可以看到,因为它以蓝色突出显示),如果您使用变量,则会发生Bad Things™。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM