D3生成柱形图添加鼠标事件(一)
2017-03-30 13:53
330 查看
直接上代码,这是动态生成的柱形图,并添加了鼠标事件
<html> <head> <meta charset="utf-8"> <title>8.1.1 鼠标交互</title> </head> <style> .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } </style> <body> <script src="../../d3/d3.v4.js" charset="utf-8"></script> <script> var dataset = [50, 43, 120, 87, 99, 167, 142]; var width = 400; //SVG绘制区域的宽度 var height = 400; //SVG绘制区域的高度 var svg = d3.select("body") //选择<body> .append("svg") //在<body>中添加<svg> .attr("width", width) //设定<svg>的宽度属性 .attr("height", height);//设定<svg>的高度属性 //x轴宽度 var xAxisWidth = 300; //y轴宽度 var yAxisWidth = 300; //x轴比例尺 var xScale = d3.scaleBand() .domain(d3.range(dataset.length)) .range([0,xAxisWidth]); //y轴比例尺 var yScale = d3.scaleLinear() .domain([0,d3.max(dataset)]) .range([0,yAxisWidth]); //外边框 var padding = { top: 30 , right: 30, bottom: 30, left: 30 }; var rect = svg.selectAll("rect") .data(dataset) //绑定数据 .enter() //获取enter部分 .append("rect") //添加rect元素,使其与绑定数组的长度一致 .attr("fill","steelblue") //设置颜色为steelblue .attr("x", function(d,i){ //设置矩形的x坐标 return padding.left + xScale(i); }) .attr("y", function(d){ //设置矩形的y坐标 return height- padding.bottom - yScale(d); }) .attr("width",xScale.bandwidth()) //设置矩形的宽度 .attr("height",function(d){ //设置矩形的高度 return yScale(d); }) .on("mouseover",function(d,i){ d3.select(this) .attr("fill","yellow"); }) .on("mouseout",function(d,i){ d3.select(this) .transition() .duration(500) .attr("fill","steelblue"); }); var text = svg.selectAll("text") .data(dataset) //绑定数据 .enter() //获取enter部分 .append("text") //添加text元素,使其与绑定数组的长度一致 .attr("fill","white") .attr("font-size","14px") .attr("text-anchor","middle") .attr("x", function(d,i){ return padding.left + xScale(i); }) .attr("y", function(d){ return height- padding.bottom - yScale(d); }) .attr("dx",xScale.bandwidth()/2) .attr("dy","1em") .text(function(d){ return d; }); var xAxis = d3.axisBottom(xScale); yScale.range([yAxisWidth,0]); var yAxis = d3.axisLeft(yScale); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left + "," + (height - padding.bottom) + ")") .call(xAxis); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left + "," + (height - padding.bottom - yAxisWidth) + ")") .call(yAxis); </script> </body> </html>
相关文章推荐
- d3柱形图响应鼠标事件(二)
- 动态生成的服务端控件,添加服务端的响应事件
- 给DataGrid添加序号、导航键、鼠标划过事件、删除确认框(转)
- 为GridView添加鼠标事件
- 为GridView添加鼠标事件
- 为窗口添加鼠标HOVER和LEAVE事件
- 给DBGrid添加鼠标滚动事件
- C#动态生成控件以及添加事件处理
- 一个ADF Javascript 添加鼠标移动事件的例子
- GridView给行添加事件(鼠标移上移下更改行背景
- C#动态添加控件,并生成事件
- 为鼠标移动事件添加新的功能-让菜单决定是否显示
- VBA:為動態生成的控件添加事件
- 利用添加onmouseover事件,做一组鼠标经过时自动换图片的图形链接
- Gridview实现添加更新及鼠标移动事件
- 给DataGrid添加序号、导航键、鼠标划过事件、删除确认框
- 为鼠标移动事件添加新的功能-在状态栏显示鼠标坐标
- 为GridView的行添加鼠标经过、点击的事件。
- jQuery为动态生成的select元素添加事件
- 在Silverlight中添加Click及DoubleClick鼠标事件