日期:2014-05-16  浏览次数:20461 次

【D3.V3.js数据可视化系列教程】(二十二)--交互图标之提示条

三种方案:

1 默认

//(1)1/2追加默认格式的提示


 .append("title")


//(1)2/2追加提示文字


 .text(function(d){
  return "This Value Is "+d.value;
 });

 

2 svg

.on("mouseover",function(d){


 //(1)取得提示显示的位置


  var xPosition=parseFloat(d3.select(this).attr("x"))+xScale.rangeBand()/2;
  var yPosition=parseFloat(d3.select(this).attr("y"))+24;


 //(2)创建提示条SVG


  svg.append("text")
  .attr("id","tooltip")//设置id便于移除提示
  .attr("x",xPosition)
  .attr("y",yPosition)
  .attr("text-anchor","middle")
  .attr("font-family","sans-setif")
  .attr("font-size","11px")
  .attr("font-weight","bold")
  .attr("fill","white")
  .text(d.value);
 })


 //(3)移除提示条SVG


 .on("mouseout",function(){
  d3.select("#tooltip").remove();//ID 选择的语法:"#tooltip"
 })

 

3 div

<!-- (1)创建div提示层 -->


 <div id="tooltip" class="hildden">
  <p><strong>提示:</strong></p>
  <p><span id="value">100</span>%</p>
 </div>

/*(2)给提示条加上样式*/


 #tooltip {
  position:absolute;
  width:200px;
  height:auto;
  padding:10px;
  background-color:white;
  
  -webkit-border-radius:10px;
  -moz-border-radius:10px;
  border-radius:10px;
  
  -webkit-box-shadow:4px 4px 10px rgba(0,0,0,0.4);
  -moz-box-shadow:4px 4px 10px rgba(0,0,0,0.4);
  box-shadow:4px 4px 10px rgba(0,0,0,0.4);
 
  pointer-events:none;
 }
 
 #tooltip.hidden{
  display:none;
 }
 
 #tooltip p{
  margin:0;
  font-family:sans-serif;
  font-size:16px;
  line-height:20px;
 }
  

//(3)更新提示条的值和位置


 .on("mouseover",function(d){
 //取得提示显示的位置
  var xPosition=parseFloat(d3.select(this).attr("x"))+xScale.rangeBand()/2;
  var yPosition=parseFloat(d3.select(this).attr("y"))/2+h/2;
  
  d3.select("#tooltip")
  .style("left",xPosition+"px")
  .style("top",yPosition+"px")
  .select("#value")
  .text(d.value);
 })
 //移除提示条SVG
 .on("mouseout",function(){


  //(4)添加隐藏类


  d3.select("#tooltip").classed("hidden",true);//ID 选择的语法:"#tooltip"
 })
 ;

 

但是最后没有出现预想的效果,不知道为什么

 

 

 

<!DOCTYPE html>
<html>
  	<head>
		<meta charset="utf-8">
		<title>testD3-18-update.html</title>
		<script type="text/javascript" src="http://localhost:8080/spring/js/d3.v3.js"></script>
	<