blog
blog copied to clipboard
Vue.js 表单focus(获取焦点)
推荐使用vue-focus这个自定义指令
组件。
用法
<input type="text" v-focus="isFocus" />
通过改变变量isFocus的值来控制表单的获焦失焦状态。
isFocus=true //获得焦点
isFocus=false //失去焦点
原理
利用vuejs的自定义指令实现,其核心代码如下:
var focus = {
inserted: function(el, binding) {
if (binding.value)
el.focus();
else
el.blur();
},
componentUpdated: function(el, binding) {
if (binding.value)
el.focus();
else
el.blur();
},
};
iOS中表单获取焦点问题
触屏设备上的Safari中focus()
有些限制。水果触屏设备的设计师们认为软键盘老是弹出来是很烦人的,用户体验不好。所以他们为表单获焦软键盘弹出设置了以下两个条件:
1) 屏幕被点击。未被点击状态下无法通过focus()
方法使表单获焦。直接点击表单或者点击其他元素然后在点击事件处理函数中调用focus()
方法使表单获焦。
2) 别的表单组件没有处于focus状态。
Basically, Safari on touchscreen devices is stingy when it comes to focus()ing textboxes. Even some desktop browsers do better if you do click().focus(). But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions:
-
The user clicked somewhere and focus() was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false}) option in jQuery.
-
Furthermore -- and this one kept me busy for a while -- focus() still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend event of the Go button, and this worked like a charm!
Vue.js 完整demo
我在线上工具JSBIN中写了一个demo,可以参考。
我是来学习的
使用的自定义指令,但是在IOS上无法获取焦点是什么原因呢?