针对textarea的Javascript OnChange检测 [英] Javascript OnChange detection for textarea

查看:96
本文介绍了针对textarea的Javascript OnChange检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,一个按钮和一些下拉列表。用户浏览ddls并回答一些问题,然后根据下拉列表在textarea中生成文本。

I have a textarea, a button and some drop down lists. The user goes through the ddls and answers some questions and I generate text in the textarea based upon the drop down lists.

在提问的某一点,按钮变为可以提交;我实际上并没有提交页面onclick,我正在做其他客户端的事情。

At a certain point in the questioning, the button becomes visable for submission; I'm not actually submitting the page onclick, I'm doing other client side stuff.

问题的要点是:我希望按钮消失(显示:none;)如果用户试图编辑textarea;直接或通过粘贴/上下文菜单。如果用户编辑textarea是可以的,但该按钮不再与应用程序相关。如何检测textarea是否被更改。

The gist of the question is this: I want the button to disappear (display:none;) if the user attempts to edit the textarea; either directly or through pasting/context menus. It is okay if the user edits the textarea, but the button is no longer relevant to the application. How do I detect if the textarea is being changed.

编辑:我不能使用jQuery。

I can't use jQuery.

推荐答案

更改事件是完全可靠的,但仅在textarea失去焦点时触发,这意味着只要用户尝试单击按钮它会消失。因此,这确实具有期望的结果,但用户体验较差。

The change event is completely reliable but only fires when the textarea loses focus, which means that as soon as the user tries to click the button it will disappear. This therefore does have the desired result but with poor user experience.

另一种方法是监控textarea的变化,这是变得棘手的地方。如果使用基于事件的方法执行此操作,则需要检测键盘输入,粘贴和拖放。并非所有浏览器都支持粘贴检测(特别是Firefox 2和Opera的所有版本都没有),所以它已经变得棘手了。更简单,更跨浏览但更脏的方法是基于轮询的方法,您可以将其与textarea的 blur 事件的处理程序结合使用,以防止用户单击的可能性民意调查之间的按钮。以下只会在重点关注textarea:

The alternative is to monitor the textarea for changes, which is where it starts to get tricky. If you do it using an event-based approach, you need to detect keyboard input, pastes and drag and drop. Not all browsers support paste detection (notably Firefox 2 and all versions of Opera do not), so it's already getting tricky. The easier, more cross-browser but dirtier method is a polling-based approach, which you can combine with a handler for the textarea's blur event to prevent the possibility of the user clicking the button between polls. The following will only poll the textarea as long as it is has the focus:

var textarea = document.getElementById("your_textarea");
textarea.onfocus = function() {
    var initialValue = textarea.value;

    function testForChange() {
        if (textarea.value != initialValue) {
            // Do the button hiding stuff
        }
    }

    textarea.onblur = function() {
        window.clearInterval(timer);
        testForChange();
        textarea.onblur = null;
    };

    var timer = window.setInterval(function() {
        testForChange();
    }, 50);
};

这篇关于针对textarea的Javascript OnChange检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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