繁体   English   中英

Textarea高亮显示魔术字。 更改字体大小和颜色。

[英]Textarea highlight magic word. change font size and colour.

我想在textarea输入中高亮一个魔术字。 我在某个地方找到了几乎可以实现我所希望看到的链接和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进行试验,但stil无法使其正常工作。

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

我不认为可以更改颜色或以任何方式将特定样式应用于textarea中的文本。

话虽如此,您可以使用div替换textarea,您可以在用户键入文本时附加div。 当您检测到关键字时,这是一个简单的任务,即在div中的文本周围包装标签。 如果执行此操作,则可能要给div一个tabindex属性,因为这将使其具有焦点。 然后,您可以在将文本插入到div中之前检查是否已选择div。

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

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

暂无
暂无

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

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