[英]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.