响应式Rich Editor预览 [英] Responsive Rich Editor Preview

查看:65
本文介绍了响应式Rich Editor预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例 .

Consider this Example.

必不可少的是JavaScript:

The essential bit is the JavaScript:

function encodeInput(editor) {
    theText = editor.val();
    theText = theText.replace(/\*\*\*(.*?)\*\*\*/, '<strong><i>$1</i></strong>', 'g');
    theText = theText.replace(/\*\*(.*?)\*\*/, '<strong>$1</strong>', 'g');
    theText = theText.replace(/\*(.*?)\*/, '<i>$1</i>', 'g');
    console.log(theText);
    $('#preview').html(theText);
}

$(function() {
    $editor = $('#editor');
    $editor.keyup(function() {
        encodeInput($(this));
    });
});

经过测试,效果很好(我确实需要\*\*\*部分,否则它不起作用).
无论如何,进入主课程

Tested and works great (I do need the \*\*\* part or it doesn't work).
Anyways, on to the main course

因为我使用的是keyup,所以脚本的响应性不是很好(例如,一旦用户放开了密钥,它只会运行").我希望它的行为更像StackOverflow上的编辑器,在其中按下键并立即发生响应.

Because I'm using keyup, the script is not very responsive (eg. it only "runs" once the user had let go of the key). I want it to behave more like the editor here on StackOverflow, where the key is pressed and response occurs immidiately.

我尝试使用keydownkeypress,但是val()属性似乎在运行时未更新,所以我真的不知道更新后的值.

I tried using keydown and keypress but it seems as if the val() attribute is not updated when it runs, so I can't really know the updated value.

如何使它更具响应性,以便在用户按下某个键时,预览会自动更新?

How can I make it more responsive, so that when the user pressed a key, the preview is automatically updated??

推荐答案

您可以在大多数浏览器中使用HTML5 input事件,而在IE<中使用propertychange事件. 9.这些事件在textarea的值更新后立即触发.

You can use the HTML5 input event in most browsers and the propertychange event in IE < 9. These events fire immediately after the textarea's value is updated.

以下是使用这些事件的更新演示:

Here's an updated demo using these events:

http://jsfiddle.net/muWm2/1/

我已经在SO的几个地方写了这个.这是其中两个:

I've written about this in a few places on SO. Here are two of them:

  • Catch only keypresses that change input?
  • jQuery keyboard events

我建议不要在每次更改textarea的值时更新预览,因为它会很快变得无响应,这对用户体验来说是一个很大的禁忌.我建议取消反弹"该事件,在这种情况下,请等待一段时间的用户不活动(例如半秒),然后再更新预览.这是一个答案和一个可能有用的链接:

I would recommend against updating the preview on every single change to the textarea's value because it could quickly get unresponsive, which is a big no-no for user experience. I'd suggest "debouncing" the event, in this case waiting for a period of user inactivity (say half a second) before updating the preview. Here's an answer and a link that may help:

  • How to trigger an onkeyup event that's delayed until a user pauses their typing?
  • Debouncing Javascript Methods by John Hann

这篇关于响应式Rich Editor预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆