这是标准的特效地址 eopa.bdstatic.com/ife%2F任务一.m…
本人的代码如下:
<!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>
.wrap{
display: inline-block;
position: relative;
left: 50%;
transform: translateX(-50%);
}
.after{
width: 0;
height: 2px;
color: #0f0f0f;
background: blue;
bottom: 0;
position: absolute;
left: 50%;
transform: translateX(-50%);
transition: all 0.5s linear;
}
span{
color: black;
transition: all 1s linear;
}
input{
border: 1px solid grey;
border-radius: 2px;
color: black;
display: block;
margin: 100px auto;
outline: none;
}
</style>
</head>
<body>
<div class="wrap">
<span>前端学院</span>
<div class="after"></div>
</div>
<input type="button" value="切换样式">
<script>
var input=document.getElementsByTagName("input")[0],
div=document.getElementsByTagName("div")[0],
span=document.getElementsByTagName("span")[0],
after=document.getElementsByClassName("after")[0];
input.onclick=function(){
if(after.style.width == "0px" || after.style.width == ""){
after.style.width = "110%";
span.style.color="blue"
}else{
after.style.width = 0;
span.style.color="black"
}
}
</script>
</body>
</html>
一开始接触到的时候,有点想当然,觉得下面那条线用border可以直接实现,实际写出来才发现大错特错。
input标签没什么好说的,着重写一下蓝线的解法。
蓝线可以用一个div标签,或者一个伪元素表示都可以,但是因为这题涉及DOM操作,对伪元素的DOM和对一般元素的写法不一样,看起来也有点不和谐,所以选择了DIV标签。
要想让它的长度从两边均匀展开,我想了两种方法:
一种写法是用margin:0 auto。
还有一种就是进行定位,left:50%和transform:translateX(-50%)。
用第二种方法有一个好处,不管字体有多长,我可以让蓝线的宽度用百分比表示,这样子就可以扩展了(联想到
我司的后端程序员写的居中方法,用margin在那里硬怼,我还要改他的前端Bug,真是人晕了)。
JS代码其实还可以改进改进,click事件后的判定方法开起来有点冗余,这里的样式改变少,如果改变的多的话
,这么写就有点累人了,所以可以将样式归类到class里,然后再添加、删除等。