简体   繁体   中英

How to scroll / move input field to top of screen with Angular when focused?

I have no clue where to start, but I am trying to make a mobile app and I have an input field in the middle of my screen. The problem is that the keyboard, that pops up, is so big, that you hardly can see the input field.

So what I want to do, just like here: Scroll page on text input focus for mobile devices?

Is to scroll down the input field to the top... when it's focused / tapped on by the user . And when you click somewhere else, the input field should go back to the place it was.

So how can I do this in Angular? Is this even possible?

Edit: I tried it with CSS , by input:focus > body , but obviously this is not possible because the input field is in the body, instead of the other way around. So if there is a CSS fix to push all other elements away and focus on the input field (or move it and blur the entire screen), I'd be happy too!

Just a simple directive would do it:

app.directive('focus-scroll', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.bind('focus', function(){
            console.log('focus triggered');
            element.scrollIntoView();
          });
        }
    }
});

And using it:

<input focus-scroll type="text" ng-model="something"/>

Weird.. i just tried the directive and indeed it didn't work. Changing the directive to use snake case did the trick though.

I created something that's maybe helpfull for people that read this. It's actually made in Angular 2+ but should work for js to.

In html:

 <input id={{uniqueID}} (focus)="scrollTo(uniqueID)" /> // item.uniqueID if array, can be numbers to if static

In the component function scrollTo(uniqueID) :

var elmnt = document.getElementById(uniqueID); // let if use typescript
elmnt.scrollIntoView(); // this will scroll elem to the top
window.scrollTo(0, 0); // this will scroll page to the top

This will ensure the input will be shown on top or on top of an inner element (div, span however you want to call it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM