d3.event 的 x 和 y 坐标在显示工具提示时不正确 [英] d3.event's x and y coordinates are incorrect while showing tooltip
问题描述
我正在尝试在水平条形图上显示工具提示.如果我向下滚动页面,此工具提示将无法正常工作.
如果条形图在视图中并且不需要滚动,这可以正常工作.但是如果我在图表上方添加更多元素,当我向下滚动时,工具提示会从鼠标指针升高.
请帮助我解决这个问题.
代码如下:
//忽略测试数据var 出生数据 = [{年份":1967,"month": "一月",出生":31502},{年份":1967,"month": "二月",出生":26703},{年份":1967,"month": "三月",出生":28853},{年份":1967,"month": "四月",出生":26958},{年份":1967,"月": "五月",出生":28591},{年份":1967,"month": "六月",出生":29545},{年份":1967,"month": "七月",出生":30086},{年份":1967,"month": "八月",出生":30947},{年份":1967,"month": "九月",出生":32338},{年份":1967,"month": "十月",出生":32296},{年份":1967,"month": "十一月",出生":30326},{年份":1967,"month": "十二月",出生":28994}]//d3 代码var minYear = d3.min(birthData, function(d) {返回 d.year;});var maxYear = d3.max(birthData, function(d) {返回 d.year;});无功宽度= 600;变量高度 = 600;var barPadding = 30;var numBars = 12;var barWidth = 10;var maxBirths = d3.max(birthData, function(d) {返回 d. 出生;});var xScale = d3.scaleLinear().domain([0, maxBirths]).range([0, 宽度]);var tooltip = d3.select('body').append('div').classed('tooltip', true);var g = d3.select('svg').attr('宽度', 宽度).attr('身高', 身高).selectAll('g').data(birthData.filter(function(d) {返回 d.year === minYear;})).进入().append('g').attr('transform', 'translate(40, 40)');g.append('rect').attr('宽度', 函数(d) {返回 xScale(maxBirths);}).attr('高度', barWidth).attr('x', 0).attr('y', function(d, i) {返回 (barWidth + barPadding) * i;}).attr('填充', '灰色');g.append('rect').attr('宽度', 函数(d) {返回 xScale(d.births);}).attr('高度', barWidth).attr('x', 0).attr('y', function(d, i) {返回 (barWidth + barPadding) * i;}).attr('填充', '蓝色').classed('原始', 真);g.append('文本').attr('x', 0).attr('y', function(d, i) {返回 (barWidth + barPadding) * i;}).text(function(d) {返回 d.month;});g.on('mousemove', showToolTip).on('mouseout', hideToolTip).on('touchstart', showToolTip).on('touchend', hideToolTip);函数隐藏工具提示(){工具提示.style('不透明度', 0);}功能 showToolTip(d) {工具提示.style('不透明度', 1).style('left', d3.event.x + 'px').style('top', d3.event.y + 'px').text(d.month + ': ' + d.births)};
svg,输入 {边距:0 自动 10px;显示:块;}.工具提示{不透明度:0;位置:绝对;指针事件:无;背景颜色:浅蓝色;边框:8px 纯蓝色;边框半径:8px;填充:15px;}
<html lang="zh-cn"><头><meta charset="UTF-8"><title>D3 出生图</title><link rel="stylesheet" href="style.css">头部><身体><div style="height: 200px; width: 200px"><h2>仪表板</h2>