[英]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? 那我怎么能在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. 编辑:我尝试使用
CSS
,通过input:focus > body
,但显然这是不可能的,因为输入字段在正文中,而不是相反。 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! 因此,如果有一个CSS修复程序将所有其他元素推开并专注于输入字段(或移动它并模糊整个屏幕),我也会很开心!
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.
它实际上是在Angular 2+中制作的,但应该适用于js。
In html: 在html中:
<input id={{uniqueID}} (focus)="scrollTo(uniqueID)" /> // item.uniqueID if array, can be numbers to if static
In the component function scrollTo(uniqueID)
: 在组件函数
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). 这将确保输入将显示在内部元素的顶部或顶部(div,span,但是您想要调用它)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.