chrome插件实现页面注入浮窗
前言
使用插件统计完数据后,通过alter展示结果,有点看不下去去,有点丑,不是很丑。那就花点时间优化一下展示效果。
思路
使用alter展示数据样式比较丑,而且需要用户点击确定关闭窗口,不然无法操作很不友好。
那么我们可以在页面中嵌入一个div浮窗来展示数据,可以定义浮窗的样式来提高用户体验,类似下面这样的效果:
实现
首先,我们要在页面中加入一个div,然后设置div的样式、设置图层位置置顶和透明度,代码如下所示:
// 创建一个浮窗元素
var div = document.createElement("div");
div.classList.add("popup");
div.style.zIndex = "9999";
div.style.opacity = "0.6";
div.innerHTML = "<h2>加班时长统计</h2>";
// 将浮窗添加到页面中
document.body.appendChild(div);
css样式代码:
.popup {
position: fixed;
top: 120px;
right: 150px;
transform: translate(-50%, -50%);
width: 300px;
padding: 20px;
background-color: rgba(0,0,0,0.8);
border-radius: 10px;
box-shadow: 0px 3px 7px rgba(0,0,0,0.20), 0px 0px 20px rgba(255,255,255,0.10);
font-family: Arial, sans-serif;
font-size: 16px;
z-index: 9999;
background-image: linear-gradient(90deg, #75d6ff, #2b32b2);
}
.popup h2 {
margin: 0;
padding-bottom: 10px;
font-size: 28px;
text-align: center;
color: #000000;
border-bottom: 1px solid #cccccc;
}
.popup p {
margin: 10px 0;
line-height: 1;
color: #333333;
text-align: justify;
}
优化
通过浮窗展示结果顺眼了一些,但是浮窗关闭会一直存在,有时候会影响操作,那么我们就加上一个关闭按钮控制浮窗关闭,js代码如下:
// 为浮窗添加一个关闭按钮
var closeButton = document.createElement("span");
closeButton.innerHTML = "×";
closeButton.classList.add("close");
// 绑定关闭按钮的点击事件
closeButton.onclick = function() {
div.style.display = "none";
};
css样式代码:
.close {
position: absolute;
top: 5px;
right: 5px;
width: 20px;
height: 20px;
border: none;
background-color: transparent;
cursor: pointer;
}
随之而来又有一个新的问题出现了,关闭后需要刷新页面才能让浮窗再次出现,而且没办法控制。想了一下,其实这个结果是在有需要的时候才看一下的,那么可以设计成默认隐藏的状态,要看了在点击查看可能会更好一点。
那么,这个触发按钮要放到哪里呢?一开始是用插件图标作为按钮触发,但是有些人会把插件隐藏起来,那就不怎么方便了。这时候我发现页面右上角有一排功能按钮,于是我就想吧这个按钮集成到原始页面中,又不会让用户觉得多余或者违和感。集成后的效果是这样的:
哈,最左边这个小圆圈就是集成的浮窗开关了,点击打开浮窗,再次点击关闭浮窗,通过简单的点击修改浮窗属性来实现的,我觉得还是挺好的。
实现的js代码:
var circleElement = document.createElement('div'); // 创建一个新的div元素
circleElement.style.width = '30px'; // 设置该元素的宽度和高度
circleElement.style.height = '24px';
circleElement.style.zIndex = "9999";
circleElement.style.opacity = "0.6";
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
var path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill", "currentColor");
path.setAttribute("d", "M12 5c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z");
svg.appendChild(path);
circleElement.appendChild(svg);
// 添加鼠标移动事件监听器
circleElement.onclick = function() {
if(div.style.display === "none"){
div.style.display = "block";
}else{
div.style.display = "none";
}
};
// 将该元素添加到文档中
document.getElementsByClassName('Header__AppList')[0].appendChild(circleElement);
THE END.
转载自:https://juejin.cn/post/7239148708700225592