效果类似百度首页音乐盒。
点击音乐右边的div可以变长或者变短。
代码:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6 <style>
7 *{
8 margin: 0;
9 padding: 0
10 }
11 body{
12 background: #121B18;
13 }
14 .txt{
15 width: 50%;
16 margin: 100px auto;
17 position: relative;
18 }
19 .mask{
20 width: 0px;
21 height: 50px;
22 overflow: hidden;
23 position: absolute;
24 left: 0;
25 display: none;
26 background: #5D6A5D;
27
28 }
29 .right{
30 float: left;
31 position: relative;
32
33 }
34 .gouzi{
35 float: left;
36 width: 30px;
37 height: 50px;
38 color: #fff;
39 text-align: center;
40 position: relative;
41 background: #4F6151;
42 }
43 .yinyue{
44 position: absolute;
45 top: 11px;
46 left: 0;
47 }
48 .content{
49 color: #fff;
50 width: 700px;
51 }
52 .clear{
53 clear: both;
54 }
55 </style>
56 </head>
57 <body>
58 <div class="txt" draggable="true">
59 <div class="gouzi" id="holdTxt"><span class="yinyue">音乐</span></div><!--钩子-->
60 <div class="right">
61 <div class="mask" id="mask"><!--遮罩层-->
62 <div class="content">我是内容</div>
63 </div>
64 <div class="clear"></div><!--清除浮动 -->
65 </div>
66 </div>
67 </body>
68 <script>
69 var holdTxt = document.getElementById("holdTxt");
70 var mask = document.getElementById("mask");
71
72 function addW(iWidthMin,iWidthMax,iSpeed){//增加/减小宽度函数,iWidthMin为最小宽度,iWidthMax为最大宽度,iSpeed为速度
73 mask.style.display="block";
74 if(iSpeed>0){//判断是增加宽度还是减小宽度
75 if(mask.offsetWidth<iWidthMax){//临界值判断
76 mask.style.width=mask.offsetWidth+iSpeed+"px";//offsetWidth:元素的宽度,边框,内边距,内容之和,不包括外边距的。
77 }
78 }else{
79 if(mask.offsetWidth>iWidthMin){
80 mask.style.width=mask.offsetWidth+iSpeed+"px";
81 }
82 }
83
84
85 }
86 var timer=null;
87 var flag=0;
88 holdTxt.onclick=function(){
89 clearInterval(timer);//清除上一次的定时器
90 if(flag==0){//如果flag==0,执行增加宽度函数
91 timer = setInterval(function(){
92 addW(0,700,10);
93 },20);
94 flag=1;//让flag=1,下次点击就执行减小宽度函数
95
96 }else if(flag==1){
97 timer = setInterval(function(){
98 addW(0,400,-10);
99 },20);
100 flag=0;
101
102 }
103
104
105 }
106 </script>
107 </html>
效果好丑(没有加太多修饰):