Javascript 鼠标悬停在屏幕上时如何显示文本

Javascript 鼠标悬停在屏幕上时如何显示文本,javascript,d3.js,Javascript,D3.js,我试过一个代码,但它不能正常工作。你能建议一种解决错误的方法吗。我对可视化还不熟悉,还处于d3.js的开始阶段 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"> </script> </head> <body> <div id="viz">

我试过一个代码,但它不能正常工作。你能建议一种解决错误的方法吗。我对可视化还不熟悉,还处于d3.js的开始阶段

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js">    </script>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">

var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);    

sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function()    {d3.select(this).append("text").attr("fill","blue").text("fill aliceblue");})


 </script>
 </body>
 </html>

var sampleSVG=d3.选择(“即”)
.append(“svg”)
.attr(“宽度”,100)
.attr(“高度”,100);
sampleSVG.append(“圆”)
.style(“笔划”、“灰色”)
.样式(“填充”、“白色”)
.attr(“r”,40)
.attr(“cx”,50)
.attr(“cy”,50)
.on(“mouseover”,function(){d3.select(this).append(“text”).attr(“fill”,“blue”).text(“fill aliceblue”);})

您正在尝试将文本元素附加到圆中,这是不可能的。 创建一个组元素并将圆和文本元素添加到该组中。 这里有一个例子

var sampleSVG=d3.选择(“即”)
.append(“svg”)
.attr(“宽度”,100)
.attr(“高度”,100);
var grp=sampleSVG.append(“g”);
变量循环=grp.append(“循环”)
.style(“笔划”、“灰色”)
.样式(“填充”、“白色”)
.attr(“r”,40)
.attr(“cx”,50)
.attr(“cy”,50);
circle.on(“mouseover”,function()){
grp.append(“文本”)
.样式(“填充”、“黑色”)
.attr(“x”,32)
.attr(“y”,52)
.text(“你好”);
});

此处建议:

创建工具提示div并将其附加到
mouseover
mousemove
mouseout
事件

var tooltip = d3.select("body")
    .append("div")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 40)
    .attr("cx", 50)
    .attr("cy", 50)
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
    (d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");}); 
工作小提琴:


请注意,在这个Fiddle中,我在脚本面板中加载了它(因为Fiddle拒绝通过http加载它,它需要https),所以您感兴趣的代码位于脚本面板的底部

请在问题中包含您遇到的错误。您可以提供一个问题的答案。还有错误是什么?当我将鼠标移到相应的圆圈上时,如果我需要将“amount”和“created at”值显示为文本,我应该怎么做。我需要5个圆圈来表示这些数据。var JSONData=[{“id”:3,“创建于”:“2013年5月5日星期日”,“金额”:12000},{“id”:1,“创建于”:“2013年5月13日星期一”,“金额”:2000},{“id”:2,“创建于”:“2013年6月6日星期四”,“金额”:17000},{“id”:4,“创建于”:“2013年5月9日星期四”,“金额”:15000},{“id”:5,“创建于”:“2013年7月1日星期一”,“金额”:16000};您是否使用
data
操作符将数据绑定到dom?请看以下教程。我相信你会明白的。只需使用
data
操作符将数据绑定到dom。下面是另一个教程,它将帮助您了解如何使用数据。