例如,当我单击按钮时,我正在寻找与scrollIntoView()
Ionic2 类似的东西。
帮助中没有详述的方法ion-content
。
例如,当我单击按钮时,我正在寻找与scrollIntoView()
Ionic2 类似的东西。
帮助中没有详述的方法ion-content
。
请看一下这个工作的plunker
您可以使用scrollTo(x,y,duration)
方法(docs)。代码非常简单,首先我们获取目标元素的位置(<p></p>
在本例中为 a),然后在scrollTo(...)
方法中使用它。首先是观点:
<ion-header>
<ion-navbar primary>
<ion-title>
<span>My App</span>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<button ion-button text-only (click)="scrollElement()">Click me</button>
<div style="height: 600px;"></div>
<!-- Notice the #target in the p element -->
<p #target>Secret message!</p>
<div style="height: 600px;"></div>
</ion-content>
以及组件代码:
import { ViewChild, Component } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
@Component({
templateUrl:"home.html"
})
export class HomePage {
@ViewChild(Content) content: Content;
@ViewChild('target') target: any;
constructor() { }
public scrollElement() {
// Avoid reading the DOM directly, by using ViewChild and the target reference
this.content.scrollTo(0, this.target.nativeElement.offsetTop, 500);
}
}
ion-content应该有滚动到特定子元素的方法,不管有多深。当前的方法还可以,但是 ionic 的目的之一是让费力、无聊的代码变得document.getElementById
过时。
这些方法也缺乏对滚动动画的控制。
因此,目前最好的选择是scrollIntoView
方法。将 id 附加到您希望滚动到的元素,然后使用 getElementbyID 调用 scrollIntoView。所以:
.html
...
<ion-row id="myElement">
...
</ion-row>
ts
...
scrollToMyElement() {
document.getElementById('myElement').scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
然后在某些 DOM 事件或按钮单击上调用该方法。如果您的元素是有条件的,这可能不起作用。而是使用条件隐藏属性,或者,如果您必须使用ngIf,则对逻辑进行计时,以便首先插入元素。
我已经尝试过使用各种其他离子 (4) UI 组件,它工作正常。
对于 Ionic-4,使用的术语有多个变化
这是 ionic-4 接受答案的修改代码
<ion-header>
<ion-navbar primary>
<ion-title>
<span>My App</span>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<button ion-button text-only (click)="scrollElement(target)">Click me</button>
<div style="height: 600px;"></div>
<!-- Notice the #target in the p element -->
<p #target>Secret message!</p>
<div style="height: 600px;"></div>
</ion-content>
组件代码:
import { ViewChild, Component } from '@angular/core';
import { IonContent } from '@ionic/angular'; // change-1
@Component({
templateUrl:"home.html"
})
export class HomePage {
@ViewChild('target', { static: false }) target: ElementRef;
@ViewChild('ion_content', { static: false }) ionContent: IonContent; //change-2 for angular > 8.0 remove this for angular 6.x
constructor() { }
public scrollElement($target) {
this.ionContent.scrollToPoint(0, $target.offsetTop, 500);
//$target (prefered if you have multiple scroll target) could be this.target.nativeElement
}
}
我会在 HTML 中使用 anker 链接。
只需给出元素和 id="scrollXYZ" 并将按钮包装在
例子:
<a href="#scrollXYZ"><button>Example</button></a>
<div id="scrollXYZ"><h2>Scroll to this</h2></div>
我试图在 Ionic 3 中执行此操作,并且由于<Element>.offsetTop
返回10
(元素顶部的填充)而不是到页面顶部的距离(更大的未知数)我最终只使用<Element>.scrollIntoView()
,对我来说效果很好。
要获取<Element>
我使用的对象document.getElementById()
,但还有许多其他选项可以用来处理它。
当我有固定内容和 div 或表单上的滚动时,我可以在 div 上使用 scrollToPoint 而不是内容吗?
在Ionic 4
滚动功能被重命名为scrollToPoint()
.