公司的后台管理系统,前端页面都以layui的样式为模板,所以级联菜单都是如下这样的:
让我感兴趣的就是右边这个小箭头的切换样式,就仅仅通过原生的span标签和CSS,就写成这样了。虽然我大致了解这种样式的原理,但是一时间让我自己写还不一定能写出来,所以就看了一下它的源码,仔细分析了一下。
先把效果图和代码发出来:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 200px; height: 200px; border: 10px dashed red; position: relative; background: black; } p { width: 0; height: 0; border-style: solid dashed dashed; border-color: #fff transparent transparent; overflow: hidden; cursor: pointer; padding-top: 10px; transition: all .2s; -webkit-transition: all .2s; position: absolute; top: 50%; right: 50%; margin-top: -3px; border-width: 6px; border-top-color: rgba(255, 255, 255, .7); } .b { margin-top: -17px; border-style: dashed dashed solid; border-color: transparent transparent #fff; right: 50%; width: 0; height: 0; overflow: hidden; cursor: pointer; transition: all .2s; -webkit-transition: all .2s; position: absolute; top: 50%; border-width: 6px; } </style></head><body> <div> <p></p> </div> <script> var p = document.querySelector("p"); console.log(window.getComputedStyle(p).marginTop) p.onclick = function () { if (window.getComputedStyle(p).marginTop === "-3px") { p.classList.add("b"); } else if (window.getComputedStyle(p).marginTop === "-17px") { p.classList.remove("b"); } } </script></body></html>CSS相关
说实话,当你第一眼看到他的CSS代码,会觉得蛮抽象的,为啥宽度和高度都是零呢?那好,我们修改一下,先增大他的宽度和高度,改变一下border的颜色。
这样一改是不是就看的更清楚了,让我们再变一下
这样就看的很明显了,归根到底它就是用上边框来构建了这个三角形。我们回归源码中初始状态比较重要的几个点来看:
border-style: solid dashed dashed;
border-color: #fff transparent transparent;
border-width: 6px;
border-top-color: rgba(255, 255, 255, .7);
它的border足足设置了6px,然后填充上边框的颜色,构建出了这个小三角形,所以我们只要关注和上边框有关的就好,其它边统统设置为不可见的。
再看变换后的代码:
border-style: dashed dashed solid;
border-color: transparent transparent #fff;就是将上边框可见变成了下边框可见,也就是这个动画中,关键点就是style和color。
JS相关
本来我想直接用jquery获取元素,但是为了考验一下自己的原生JS能力,就用原生的写了,结果就在给p标签的click事件设置判定条件时遇到了一个小问题:
p.style只能获取dom元素的内联CSS样式,而我原有的css直接放在class里面,所以使用了window.getComputedStyle()来获取样式,注意,这个方法是属于window对象下面的,不要错写成dom元素下面的。