本文實現的效果如下:
圖一:

圖二:

思路:
將粉色區域絕對定位,right值為藍色區域的寬度,父元素相對定位,藍色區域右浮動即可。
好處:
這樣做的好處在於,相對於用js來實現粉色區域高度的自適應,這種方法可以提高性能,我們在寫效果的時候,能用css來實現的,盡量不要用js來實現。
css在書寫的時候很簡單,但是css也會關系到性能的優化問題,這里隨便提出幾點:
1.盡量不要使用層級選擇器,
2.不要使用元素選擇器,
3.不要使用屬性選擇器等。
上述這些選擇器都會影響性能問題。
代碼如下:
<!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <meta http-equiv="X-UA-Compatible" content="ie=edge">
7 <title>Document</title>
8 <style>
9 *{
10 margin: 0;
11 padding: 0;
12 }
13 .box{
14 width: 800px;
15 overflow: hidden;
16 position: relative;
17 margin: 50px auto;
18 }
19 .left{
20 position: absolute;
21 top: 0;
22 right: 600px;
23 bottom: 0;
24 left: 0;
25 background: pink;
26 }
27 .right{
28 width: 600px;
29 height: 200px;
30 float: right;
31 background: blue;
32 }
33 .btn-wrap{
34 width: 800px;
35 margin: 0 auto;
36 overflow: hidden;
37 }
38 .btn{
39 width: 50px;
40 height: 30px;
41 float: right;
42 margin-left: 50px;
43 background: #eee;
44 }
45 </style>
46 </head>
47 <body>
48 <div class="box">
49 <div class="left"></div>
50 <div class="right"></div>
51 </div>
52
53 <div class="btn-wrap">
54 <button class="btn add">加</button>
55 <button class="btn sub">減</button>
56 </div>
57 <script>
58 var right = document.getElementsByClassName("right")[0],
59 add = document.getElementsByClassName("add")[0],
60 sub = document.getElementsByClassName("sub")[0];
61
62 add.onclick = () => {
63 right.style.height = right.offsetHeight + 20 + 'px';
64 }
65
66 sub.onclick = () => {
67 right.style.height = right.offsetHeight - 20 + 'px';
68 }
69 </script>
70 </body>
71 </html>
有錯誤之處,歡迎指教。謝謝,閱讀。