移动端(html5)微信公众号下用keyup实时监控input值的变化无效

来源:互联网 发布:做微课用什么软件 编辑:程序博客网 时间:2024/06/05 20:47

搜索框依据用户输入的值实时检索,一开始自然而然想到keyup,在拼音状态时,啥问题也没有,

问题1:切换到中文输入法,问题出来了,keyup事件不灵便了,后来在网上搜了下,找到了思路,

问题2:微信公众平台开发时,客户提需求“输入框中输入内容时,输入框后边显示清除按钮,清除输入框中的内容”,使用“keyup”事件时在中文输入法下部分按键keyup事件无效,


方法一:主要是给搜索框注册focus事件,隔个时间去检索下,贴出代码

<script language="javascript" type="text/javascript" src="jquery.js"></script>    <script>    $(function () {        $('#wd').bind('focus',filter_time);    })    var str = '';    var now = ''    filter_time = function(){        var time = setInterval(filter_staff_from_exist, 100);        $(this).bind('blur',function(){            clearInterval(time);        });    };    filter_staff_from_exist = function(){        now = $.trim($('#wd').val());        if (now != '' && now != str) {            console.log(now);        }        str = now;    }    </script>


方法二:用 input 和 propertychange事件可以解决, 

本人测试只能用dom2的绑定方法使用 如 document.getElementById('box').addEventListener('input',function(){...dosomething...},false); 

html><head><script type="text/javascript" src="http://www.zlovezl.cn/static/js/jquery-1.4.2.min.js"></script></head><body>    <p>        使用oninput以及onpropertychange事件检测文本框内容:    </p>    <p>        <input type="text" name="inputorp_i" id="inputorp_i" autocomplete="off"/>        <span id="inputorp_s"></span>        <script type="text/javascript">            //先判断浏览器是不是万恶的IE,没办法,写的东西也有IE使用者            var bind_name = 'input';            if (navigator.userAgent.indexOf("MSIE") != -1){                bind_name = 'propertychange';            }            $('#inputorp_i').bind(bind_name, function(){                $('#inputorp_s').text($(this).val());            })        </script>    </p></body></html>

可是也有人说用jq方式绑定即可 如:

$('#input').bind('input propertychange', function() {                alert("....")            });


或者原生:
<script type="text/javascript">// Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9function OnInput (event) {    alert ("The new content: " + event.target.value);}// Internet Explorerfunction OnPropChanged (event) {    if (event.propertyName.toLowerCase () == "value") {        alert ("The new content: " + event.srcElement.value);    }} </script><body>    <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" /></body>

最后需要注意的是:oninput 和 onpropertychange 这两个事件在 IE9 中都有个小BUG,那就是通过右键菜单菜单中的剪切和删除命令删除内容的时候不会触发,而 IE 其他版本都是正常的,目前还没有很好的解决方案。不过 oninput & onpropertychange 仍然是监听输入框值变化的最佳方案..




2 0