目录

Obtaining Page Node Information

Before specifying the attributes and position of the target node, you need to obtain the page node information as follows.

HXML Node Information

The node information query API is used to obtain node information such as their attributes, styles, and on-screen positions.

It is most commonly used to query the current position of a node and the scroll position of the view. The sample code is as follows:

const query = has.createSelectorQuery();
query.select('#elem-id').boundingClientRect(function (res) {
  const top = res.top; // Top margin
  console.info(`boundingClientRect, top: ${top}`);
});
query.selectViewport().scrollOffset(function (res) {
  const scrollTop = res.scrollTop; // Vertical scroll offset of the visible scroll view
  console.info(`scrollOffset, scrollTop: ${scrollTop}`);
});
query.exec();

In the preceding example, #elem-id is a node selector, which is slightly different from the CSS selector. For details, see SelectorQuery.select.

In custom components or pages that contain custom components, you are advised to use this.createSelectorQuery instead of has.createSelectorQuery. This ensures that nodes can be selected within the correct scope.

Intersection Status of HXML Nodes

The has.createIntersectionObserver API is used to listen for the intersection status of two or more component nodes in the layout. It is commonly used to determine whether a node is visible to users and its visible proportion.

Below are the involved concepts:

The following sample code allows the callback to be triggered each time the target node (specified by .target-elem) enters or leaves the page display area:

Page({
  onLoad: function () {
    this.createIntersectionObserver().relativeToViewport().observe('.target-elem-class', (res) => {
      const id = res.id; // ID of the target node
      const dataset = res.dataset; // Dataset of the target node
      const intersectionRatio = res.intersectionRatio; // Ratio of the intersection area to the layout area of the target node
      const intersectionRect = res.intersectionRect; // Intersection area
      const left = intersectionRect.left; // Left boundary coordinate of the intersection area
      const top = res.intersectionRect.top; // Top boundary coordinate of the intersection area
      const width = res.intersectionRect.width; // Width of the intersection area
      const height = res.intersectionRect.height; // Height of the intersection area
      console.info(`relativeToViewport, observe, id: ${id}`);
      console.info(`relativeToViewport, observe, intersectionRect: [${left}, ${top}, ${width}, ${height}]`);
    });
  }
});

In custom components or pages that contain custom components, you are advised to use this.createIntersectionObserver instead of has.createIntersectionObserver. This ensures that nodes can be selected within the correct scope.