How to realize input input box to get focus automatically in element
This article mainly introduces how to achieve the element input input box to automatically get the focus, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
When you do a form in a recent project, you need to automatically scroll to the comment box and let the comment box focus automatically, which requires you to manually trigger the focus status of the input box.
However, element does not support the autofocus attribute, so the focus effect can only be obtained through the native js effect.
Document.getElementById (input) .focus ()
Or you can use the ref attribute of vue to achieve the focus effect:
The principle is actually very simple. Element has provided the focus method, but the document does not specify how to call it. Here is to add the ref attribute to the el-input tag, and then call the method directly where needed.
This.$nextTick (() = > {this.$refs.input.focus ()})
Note: a page can only have one focus effect.
Last, vue also supports custom directives
This element gets focus when the page loads (note: autofocus doesn't work on mobile Safari). In fact, as long as you haven't clicked anything since you opened the page, the input box should still be in focus. Now let's implement this function with instructions:
/ / register a global custom directive `v-focus`Vue.directive ('focus', {/ / when the bound element is inserted into the DOM. Inserted: function (el) {/ / focus element el.focus () / / element-ui el.children [0] .focus () / / element changes, such as show or parent element change can be delayed or judged setTimeout (_ = > {el.children [0] .focus ()}}) Thank you for reading this article carefully I hope the article "how to achieve the automatic focus of input input box in element" shared by the editor is helpful to everyone. At the same time, I also hope that you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!