您的位置:首页 > Web前端 > CSS

css实现高度动态变化自如 新手写着娱乐

2017-08-15 16:42 176 查看
思路:
  将粉色区域绝对定位,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>


有什么不妥的地方希望可以指出来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: