文本区高亮魔术字.更改字体大小和颜色

Textarea highlight magic word. change font size and colour.

本文关键字:颜色 字体 高亮 魔术 文本区      更新时间:2023-09-26

我想在文本区输入一个神奇的单词高亮显示。我在某个地方找到了代码,几乎做了我想要的,见下面的链接和Javascript代码:

http://mootools.net/demos/?demo=Element.Event

下面是javascript代码

window.addEvent('domready', function() {
  var textarea = $('myTextarea'), log = $('log').setStyle('opacity', 0);
  // We define the highlight morph we're going to
  // use when firing an event
  var highlight = new Fx.Morph(log, {
    duration: 1500,
    link: 'cancel',
    transition: 'quad:out'
  });
  // Here we start adding events to textarea.
  // Note that 'focus' and 'keyup' are native events, while 'burn'
  // is a custom one we've made
  textarea.addEvents({
    focus: function() {
        // When focusing, if the textarea contains value "Type here", we
        // simply clear it.
        if (textarea.value.contains('Type here')) textarea.set('value', '');
    },
    keyup: function() {
        // When user keyups we check if there are any of the magic words.
        // If yes, we fire our custom event burn with a different text for each one.
        if     (textarea.value.contains('hello')) textarea.fireEvent('burn', 'hello world!');
        else if (textarea.value.contains('moo')) textarea.fireEvent('burn', 'mootools!');
        else if (textarea.value.contains('pizza')) textarea.fireEvent('burn', 'Italy!');
        else if (textarea.value.contains('burn')) textarea.fireEvent('burn', 'fireEvent');
        // note that in case of 'delayed', we are firing the event 1 second late.
        else if (textarea.value.contains('delayed')) textarea.fireEvent('burn', "I'm a bit late!", 1000);
    },
    burn: function(text) {
        // When the textarea contains one of the magic words
        // we reset textarea value and set the log with text
        textarea.set('value', '');
        log.set('html', text);
        // then we start the highlight morphing
        highlight.start({
            backgroundColor: ['#fff36f', '#fff'],
            opacity: [1, 0]
        });
    }
  });
});

我不想清除文本区域,我想通过改变特定单词的字体颜色和增加字体大小来突出显示文本区域内的神奇单词。(只有魔法字,没有别的)

我试着用JSFIDDLE做实验,但仍然不能让它工作。

http://jsfiddle.net/api/post/mootools/1.4/dependencies/more/

我认为不可能改变文本区域的颜色或以任何方式对文本应用特定的样式。

话虽如此,您可以用div替换文本区,可以在其中添加文本作为用户键入的内容。当你检测到一个关键字时,这是一个简单的任务,在div的文本周围包装一个标签。如果你这样做,你可能想给div一个tabindex属性,因为这将允许它有焦点。然后,您可以在插入文本之前检查div是否被选中。

如果你真的想使用一个文本区域作为输入,那么你也可以尝试在文本区域上浮动一个div或span元素,然后让你的burn函数设置浮动div的文本,并使用CSS将其定位在用户输入的单词上。您可以使用以下命令来确定光标在文本区域中的位置:

var textarea = document.getElementById('textarea'),
    lineNum = textarea.selectionStart % textarea.cols,
    colNum = textarea.selectionStart - (textarea.cols * lineNum);