D3.js 提示tip事件:
经常有这样的需求,图形上某一块区域需要做鼠标事件,移入需要展示一些数据之类的需求,其实这里就可以用到tips的功能了。
步骤其实并不麻烦,分为几步就行了:
1.生成svg的样式
2.建立tips,
3.添加鼠标事件
<body>
<svg width="500" height="400" style="border: 1px solid pink;" >
<div></div> <!-- 会报错 -->
</svg>
<div class="qq"></div>
</body>
</html>
<script>
// 注意这里是需要重新生成一个svg区域,因为如果直接以svg为最外层的元素进行定位的话,是无法显示tips的,svg只能包含符合要求元素,
const svg = d3.select(".qq").append("svg").attr("width",500).attr("height",400)
d3.select("svg").append("circle").attr("r", 20)
.attr("cx", 100)
.attr("cy", 100)
.attr("fill", "pink")
// 添加tips
const tips = d3.select(".qq")
.append("div")
.style("position", "absolute") // 设置定位
.style("visibility", "hidden") // 最开始隐藏起来
.style("background-color", "white")
.style("border", "1px solid pink")
.html("<span>tips!</span>" +
"<span>这里放入内容</span>" +
"<img width='200' height='200' style='{background-size: 100% 100%}' src='https://img0.baidu.com/it/u=87377348,1938790525&fm=253&fmt=auto&app=138&f=JPEG?w=334&h=500'></img>" +
"<span>十元最美!!!</span>");
// 添加鼠标事件 注意是给圆点加
d3.select("circle")
.style('cursor', 'pointer')
.on("mouseover", function () {
return tips.style("visibility", "visible")
})
.on("mousemove", function () {
return tips.style("top", "80px").style("left", "150px")
})
.on("mouseout", function () {
return tips.style("visibility", "hidden")
})
</script>
那如果是从接口获取的数据,需要在图上显示出来呢,也是一样的操作步骤
<body>
<div class="qq"></div>
</body>
</html>
<script>
const svg = d3.select(".qq").append("svg").attr("width", 700).attr("height", 400).style("border", "1px solid pink")
// 模拟数据 这里采用比较简单的原点
const dataList = [
{ 'r': 10, 'x': 80, y: 180, 'color': 'orange' },
{ 'r': 20, 'x': 150, y: 250, 'color': 'blue' },
{ 'r': 30, 'x': 85, y: 250, 'color': 'purple' },
{ 'r': 15, 'x': 323, y: 100, 'color': 'pink' },
{ 'r': 25, 'x': 500, y: 250, 'color': 'green' },
]
// 绘制图形
const circle = d3.select("svg")
.selectAll("circle")
.data(dataList)
.join("circle")
.attr("r", (d) => d.r)
.attr("cx", (d) => d.x)
.attr("cy", (d) => d.y)
.attr("fill", (d) => d.color)
.style('cursor', 'pointer');
// 添加tips
const tips = d3.select(".qq")
.append("div")
.style("visibility", "hidden")
.style('position', 'absolute')
.style("background-color", "white")
.style("border", "1px solid pink")
.style("padding", "5px")
//添加事件
circle.on('mouseover', function () {
tips.style("visibility", "visible")
})
.on('mousemove', function (d) {
console.log(event); // 鼠标事件对象
console.log(this); // 这里的this就表示当前选择的元素
let element = d3.pointer(event, this) //d3.pointer(事件, target) 获取鼠标的x,y 坐标。 d3.pointer()方法,详细可以看我上一篇推文
console.log(element);
tips.style("visibility", "visible")
.style('left', element[0] + 40 + 'px')
.style('top', element[1] + 'px')
.html(
`我是${d.target.__data__.color} 圆,我的半径是 ${d.target.__data__.r}`
)
})
.on('mouseleave', function () {
tips.style("visibility", "hidden")
});
</script>