移動端(html5)Safari下用keyup實時監控input值的變化無效
阿新 • • 發佈:2019-01-09
搜尋框依據使用者輸入的值實時檢索,一開始自然而然想到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事件可以解決,
<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("....")
});
四、原生js繫結
<script type="text/javascript">
// Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
function OnInput (event) {
alert ("The new content: " + event.target.value);
}
// Internet Explorer
function 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 仍然是監聽輸入框值變化的最佳方案..