展开和收回功能,并且可自行调配宽度

110 阅读1分钟

思路:左边和右边两个盒子,左边盒子宽度写死,右边盒子使用flex:1,自适应剩余宽度。后面只需改变左边盒子宽度即可完成上述功能。

目前项目采用的是组件来实现的,个人觉得太过于麻烦,有点大材小用了,使用vue的自定义指令就可以完美实现

  <div id="app">
    <div id="left">
      <div class="moveBtn" v-move></div>
      <div class="btn" @click="btn">{{ btnContext }}</div>
    </div>
    <div id="right"></div>
  </div>
</template>

<script>
export default {
  directives: {
    "move" (el) {
      el.onmousedown = function (e) { //鼠标按下
        var init = e.clientX; //获取鼠标当前位置
        var parent = document.getElementById("left");
        var initWidth = parent.offsetWidth; //获取当前元素宽度
        document.onmousemove = function (e) { //鼠标移动时触发
          var end = e.clientX;
          var newWidth = end - init + initWidth; //计算出原来的宽度然后将
          parent.style.width = newWidth + "px"; //左边为自适应,所以给右边的盒子设置宽度就可以完成拖拉的效果
        };
        document.onmouseup = function () {  //鼠标弹起后触发
          document.onmousemove = document.onmouseup = null;
        };
      };
    }
  },
  name: 'App',
  data(){
    return {
      btnContext:"《"
    }
  },
  methods:{
    btn(e){
      var init = e.clientX; //获取鼠标当前位置
      var parent = document.getElementById("left");
      if (init > 5) { //鼠标当前位置大于5就收回
        parent.style.width = 5 + "px";   //收回:将当前右边盒子的宽度设置为5px
        this.btnContext = "》" //这里直接用书名号代替了,项目中一般使用的是字体图标
      }

      if (init <= 20) { //鼠标当前位置小于等于20就会展开
        parent.style.width = 300 + "px";  //展开:将当前右边盒子的宽度设置为300
        this.btnContext = "《" //这里直接用书名号代替了,项目中一般使用的是字体图标
      }
    }
  }
}
</script>

<style>
html,body{
  margin: 0;
  padding: 0;

}
#app {
  display: flex;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100vh;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}
#left{
  position: relative;
  width: 300px;
  height: 100%;
  background-color: rgba(255, 50, 0, 0.5);
}
#right{
  flex: 1;
  background-color: rgba(0, 50, 255, 0.5);
}
.moveBtn{
  cursor: col-resize;
  position: absolute;
  top: 0;
  right: -5px;
  width: 10px;
  height: 100%;
  background-color: transparent;
}
.btn{
  cursor:pointer;
  position: absolute;
  top: 50%;
  transform: translate(0,-50%);
  right: -15px;
  width: 30px;
  height: 100px;
  background-color: red;
  border-radius: 10px 50% 50% 10px;
  line-height: 100px;
  text-align: center;
}
</style>