获取页面节点信息
收藏我的收藏
TTML 节点信息
节点信息查询 API 可以用于获取节点属性、样式、在界面上的位置等信息。
最常见的用法是使用这个接口来查询某个节点的当前位置,以及界面的滚动位置。
示例代码:
const query = tt.createSelectorQuery(); query.select("#the-id").boundingClientRect(function (res) { res.top; // The upper boundary coordinates of the #the-id node (relative to the display area) }); query.selectViewport().scrollOffset(function (res) { res.scrollTop; // The vertical scroll position of the display area }); query.exec();
在自定义组件或包含自定义组件的页面中,推荐使用
this.createSelectorQuery
来代替 tt.createSelectorQuery
,这样可以确保在正确的范围内选择节点。TTML 节点布局相交状态
节点布局相交状态 API 可用于监听两个或多个组件节点在布局位置上的相交状态。这一组 API 常常可以用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见。
这一组 API 涉及的主要概念如下:
- •参照节点:监听的参照节点,取它的布局区域作为参照区域。如果有多个参照节点,则会取它们布局区域的 交集 作为参照区域。页面显示区域也可作为参照区域之一。
- •目标节点:监听的目标,默认只能是一个节点(使用 selectAll 选项时,可以同时监听多个节点)。
- •相交区域:目标节点的布局区域与参照区域的相交区域。
- •相交比例:相交区域占参照区域的比例。
- •阈值:相交比例如果达到阈值,则会触发监听器的回调函数。阈值可以有多个。
以下示例代码可以在目标节点(用选择器
.target-class
指定)每次进入或离开页面显示区域时,触发回调函数:tt.createIntersectionObserver() .relativeToViewport() .observe(".target-class", (res) => { res.id; // Target node ID res.dataset; // Target node dataset res.intersectionRatio; // The percentage of the intersection area in the layout area of the target node res.intersectionRect; // Intersection area res.intersectionRect.left; // Left boundary coordinates of the intersection area res.intersectionRect.top; // Upper boundary coordinates of the intersection area res.intersectionRect.width; // Width of the intersection area res.intersectionRect.height; // Height of the intersection area });
在自定义组件或包含自定义组件的页面中,推荐使用
this.createIntersectionObserver
来代替 tt.createIntersectionObserver
,这样可以确保在正确的范围内选择节点。