You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从getBoundingClientRectAsync返回的Promise结果中获取left属性值

问题原因

getBoundingClientRectAsync 属于AMP提供的异步API,返回值是Promise实例而非直接的坐标对象。你直接访问Promise实例上的left属性自然会返回undefined,只有等Promise状态变为fulfilled后,才能拿到内部存储的坐标结果。

解决方案

方案1:使用async/await语法(推荐)

将事件回调函数声明为异步函数,用await等待Promise执行完成后再取值:

button.addEventListener("mouseenter", async function(event){
   let target = event.target;
   // 等待异步方法返回结果
   let coords = await target.getBoundingClientRectAsync();
   console.log(coords.left); // 可正常获取left属性
});

方案2:使用.then链式调用处理Promise结果

通过Promise自带的.then方法接收异步返回的坐标对象:

button.addEventListener("mouseenter", function(event){
   let target = event.target;
   target.getBoundingClientRectAsync().then(coords => {
       console.log(coords.left); // 回调内可正常获取属性
   })
   // 可追加.catch处理异步调用异常
   .catch(err => console.error('获取坐标失败', err));
});

内容的提问来源于stack exchange,提问作者la_petite_kozel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 04:06:12