繁体   English   中英

如何在聚焦时使用Angular将输入字段滚动/移动到屏幕顶部?

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

我不知道从哪里开始,但我正在尝试创建一个移动应用程序,我的屏幕中间有一个输入字段。 问题是弹出的键盘太大了,几乎看不到输入字段。

那么我想做什么,就像这里一样: 滚动浏览移动设备的文本输入焦点页面?

将输入字段向下滚动到顶部...当用户聚焦/点击时 当您单击其他位置时,输入字段应该返回到它所在的位置。

那我怎么能在Angular中做到这一点? 这甚至可能吗?

编辑:我尝试使用CSS ,通过input:focus > body ,但显然这是不可能的,因为输入字段在正文中,而不是相反。 因此,如果有一个CSS修复程序所有其他元素推开并专注于输入字段(或移动它并模糊整个屏幕),我也会很开心!

只需一个简单的指令即可:

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

并使用它:

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

很奇怪..我刚刚尝试了这个指令,但确实没用。 改变指令使用蛇案就可以了。

我创造了一些可能对阅读此内容的人有用的东西。 它实际上是在Angular 2+中制作的,但应该适用于js。

在html中:

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

在组件函数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

这将确保输入将显示在内部元素的顶部或顶部(div,span,但是您想要调用它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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