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

页面滚动状态下,如何通过D3.js实现点击元素后Div的页面固定位置精准定位

Fix D3.js Div Positioning Issue When Page Scrolling

Let's break down why your div is misbehaving when the page scrolls, and fix it step by step.

The Root Cause

Your current code uses position:absolute for the div, which positions elements relative to the nearest non-static parent (usually the document root). But the coordinates you get from p.matrixTransform(p.getScreenCTM()) are viewport-relative screen coordinates—they represent where the point is within the browser's visible window, not the entire document. When you scroll the page, the viewport shifts relative to the document, but your pt.y/pt.x values don't account for this scroll offset. That's why the div appears to move up when you scroll down: the absolute position is stuck to the viewport's initial position instead of the document's fixed point.

Solutions

Option 1: Fix the Div to the Viewport (Stays in Place When Scrolling)

If you want the div to remain in a fixed position within the browser window (doesn't move when scrolling), change the CSS position to fixed instead of absolute:

#event_description_div {
  position: fixed; /* Changed from absolute */
  top: 50px;
  left: 50px;
  overflow-y: scroll;
  height: 100px;
}

Your existing JavaScript code should work as-is here, because fixed positioning uses viewport-relative coordinates, which matches the pt values you're calculating from the SVG.

Option 2: Fix the Div to a Permanent Document Position (Moves With Scrolling)

If you need the div to stay anchored to a specific point in the document (so it scrolls along with the page), you need to adjust your coordinates to include the page's scroll offset. Modify your JavaScript to add window.scrollX and window.scrollY to the calculated position:

// Executed when clicking an element
let p = svg.createSVGPoint();
p.x = 0;
p.y = event_desc_pos_y;
let pt = p.matrixTransform(p.getScreenCTM());

// Account for page scroll offset
const scrollX = window.scrollX || document.documentElement.scrollLeft;
const scrollY = window.scrollY || document.documentElement.scrollTop;

let event_desc_div = d3.select('#event_description_div')
  .style('top', (pt.y + scrollY) + 'px')
  .style('left', (pt.x + scrollX) + 'px')
  .style('width', width + 'px');

Keep your original position:absolute CSS here—this adjustment converts the viewport-based pt coordinates to document-based coordinates that absolute positioning uses.

Verify the Fix

  • For Option 1: Scroll the page, and the div should stay locked to the same spot in your browser window.
  • For Option 2: Scroll the page, and the div should remain aligned with the intended point in your SVG/document, moving as you scroll.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:04:08