可视化 | 【d3】力导向关系图优化(搜索+刷新)
前期回顾:【d3】力导图优化,本文主要是基于上篇代码,以代码段添加的方式实现优化。
📚优化内容
- 添加搜索框功能,实现搜索高亮。
- 双击空白处,图表还原的同时搜索框清零。
- 添加刷新按钮,页面刷新。
📚html和css优化
🐇搜索框部分
- 搜索框部分的样式直接套的模板,修改了对应的颜色和div在页面的位置(忘记存参考博客了,后续找回来了再放(>人<;)
- html部分
<div class="search-box"> <input type="text" id="searchBox" class="search-txt" placeholder="name?" /> <a class="search-btn"> <i class="fa fa-search" aria-hidden="true"></i> </a> </div>
- css部分
.search-box{ position: absolute; left: 20%; top: 10%; transform: translate(-50%,-50%); background-color: #a04c3b; height: 30px; margin-top: 20px; padding: 10px; border-radius: 40px; } .search-txt{ border:none; background: none; outline: none; float: left; padding: 0; color: #fff; font: 16px sans-serif; line-height: 30px; width: 0; /* 动画过渡 */ transition: 0.4s; } .search-txt::placeholder{ color: #ffffff67; } .search-btn{ color: #fff; float: right; width: 3cap; height: 30px; border-radius: 50%; background-color: #a04c3b; /* 弹性布局 水平垂直居中 */ display: flex; justify-content: center; align-items: center; cursor: pointer; /* 动画过渡 */ transition: 0.4s; } .search-box:hover .search-txt{ width: 200px; padding: 0 6px; } .search-box:hover .search-btn{ background-color: #a04c3b; }
- 以及一个外部样式表——那个放大镜的效果实现
<link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
- 最终效果
- 静置
- 鼠标悬浮
- 输入
- 静置
🐇刷新按钮部分
- html部分:下载了一个刷新icon,套了个div。
<div class="button"> <img id="editBtn" src="./assects/images/刷新.png"> </div>
- css部分:用div确定位置,借助
:hover
时的scale
设置,实现选定时放大。.button{ position: absolute; left: 90%; top: 5%; } #editBtn{ height: 30px; width: 30px; } #editBtn:hover{ scale:1.2; }
📚js
🐇搜索框部分
- 在创建部分添加搜索框搜索功能:关注每次搜索前先还原,不然历史搜索高亮结果会有干扰。
var searchBox = document.getElementById('searchBox'); searchBox.addEventListener('input', function() { var searchName = this.value.trim(); if (searchName !== '') { // 每次搜索之前先还原 dependsNode = dependsLinkAndText = []; _this.highlightObject(null); // 节点姓名匹配 var matchedNode = defaultConfig.data.nodes.find(function(node) { return node.name.toLowerCase() === searchName.toLowerCase(); }); _this.highlightObject(matchedNode); } else { _this.highlightObject(null); } });
- 优化空白处双击效果:使得空白处双击后,高亮清除图表还原的同时搜索框内容清空。
// 在整个页面上绑定双击事件处理函数 d3.select(".network").on('dblclick',function(){ // 当双击页面其他区域时,取消所有节点、连接线和连线上的文本的高亮显示,并重置依赖节点和连接线数组 dependsNode = dependsLinkAndText = []; _this.highlightObject(null); // 同时清空输入框 d3.selectAll("#searchBox").property("value", ""); });
🐇刷新部分
- 刷新功能就直接了当了,直接用
click
事件绑定location.reload();
,实现页面刷新。d3.json("./data/people.json", function(json) { // 创建部分 function GroupExplorer(wrapper,config){...} // 实例应用 new GroupExplorer('.network',{ data:json }); document.getElementById('editBtn').addEventListener('click', function() { location.reload(); }); });