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

在Google Web Designer中拖拽对象时,如何获取动画对象的位置值?

在Google Web Designer中拖拽时获取动画对象位置信息的实现方案

核心需求

拖拽指定对象过程中,实时获取另一沿Y轴运动的动画对象的以下位置信息:

  • X轴参数
  • left像素值
  • top像素值

修改后的拖拽事件代码

假设目标动画对象的ID为animatedElement,你可以在拖拽事件中添加位置获取逻辑,具体代码如下:

Dragstart事件代码(无需修改)

gwd.dragger = this;
event = (event.changedTouches ? event.changedTouches[0] : event);
gwd.s = window.getComputedStyle ? getComputedStyle(this, null) : this.currentStyle;
gwd.dX = event.pageX - parseInt(gwd.s["left"]);
gwd.dY = event.pageY - parseInt(gwd.s["top"]);

Dragmove事件代码(添加位置获取逻辑)

if (gwd.dragger) {
    event = (event.changedTouches ? event.changedTouches[0] : event);
    // 更新拖拽对象位置
    gwd.actions.events.setInlineStyle(gwd.dragger.id, "left:" + (event.pageX - gwd.dX) + "px; top:" + (event.pageY - gwd.dY) + "px");
    
    // 获取目标动画对象的位置信息
    const animatedEl = document.getElementById("animatedElement");
    if (animatedEl) {
        // 方法1:通过计算样式获取left/top值
        const elStyle = window.getComputedStyle ? getComputedStyle(animatedEl, null) : animatedEl.currentStyle;
        const elLeft = parseInt(elStyle["left"]);
        const elTop = parseInt(elStyle["top"]);
        // 获取相对文档的X轴全局位置
        const elX = animatedEl.getBoundingClientRect().left + window.scrollX;
        
        // 方法2:通过边界矩形获取视口位置,可转换为文档全局位置
        const rect = animatedEl.getBoundingClientRect();
        const docX = rect.left + window.scrollX;
        const docY = rect.top + window.scrollY;
        
        // 此处可添加位置信息的业务逻辑,比如打印或用于其他交互
        console.log("动画对象left:", elLeft, "top:", elTop, "X轴位置:", elX);
        // console.log("动画对象文档全局位置X:", docX, "Y:", docY);
    }
}

Dragstop事件代码(无需修改)

gwd.dragger = null;

关键说明

  1. ID替换:将代码中的animatedElement替换为你实际使用的动画对象ID
  2. 位置获取方式选择:
    • getComputedStyle直接读取元素CSS样式值,适合元素使用left/top定位的场景
    • getBoundingClientRect获取元素相对视口的位置,结合滚动距离可转换为全局文档位置,兼容性更强
  3. 实时性保障:位置获取逻辑放在Dragmove事件内,确保拖拽过程中实时更新数据

内容的提问来源于stack exchange,提问作者Lin Thike Aung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:52:12