最近在做的项目有个效果是要实现div随意拖拽改变大小,前端框架选择的是vue.js,UI用的是element,拖拽效果可以很简单的实现,但是在拖拽过程中发现会对其他元素实现全选效果,因此最后选择使用元素属性设置将全选功能关闭,当拖拽取消时全选功能还原;
简单的消息提示框(效果图如下,通过选中消息提示框当前行可以进行上下随意拖拽):
HTML代码如下,
<template>
<div class="msgbox">
<el-card class="box-card" v-if="msgshow" ref="msgSpan">
<div class="msgbox-top" v-on:mousedown="onmouse">
<h4>消息提示框</h4>
<span class="clear" @click="clearMesBox"><span>清空提示框</span><i class="el-icon-circle-cross" @click="msghide"></i></span>
</div>
<div class="msgbox-news" ref="msgtop">
<div v-for="item in items" :key="item" class="text item" @dblclick="goLook(item)" v-bind:style="{'background': item.bgcolor}">
{{item.value}}
</div>
</div>
</el-card>
</div>
</template>
拖拽效果的原理其实很简单,以下是功能实现的JS代码:
onmouse:function(){
var that=this;
var hei=window.innerHeight;//获取窗体高度
var oDiv = this.$refs.msgSpan.$el;//vue通过$refs获取元素属性
var oTop = this.$refs.msgtop;
that.$refs.msgSpan.$parent.$parent.$parent.$el.style.webkitUserSelect='none';//添加样式控制拖拽时禁止全选动作
that.$refs.msgSpan.$parent.$parent.$parent.$el.style.mozUserSelect='none';//添加样式控制拖拽时禁止全选动作
oDiv.onmousedown = function(ev){
var disY = ev.clientY - oDiv.offsetTop;
var web='-webkit-user-select';
// console.log(ev.clientY)
// console.log(oDiv.offsetTop)
document.onmousemove = function(ev){
// var t = ev.clientY-disY;
var t = hei-ev.clientY;
if(t<=180){
oTop.style.height=170+'px';
}else{
oDiv.style.height = t+'px';
oTop.style.height = t - 30 +'px';
}
};
document.onmouseup = function(){
document.onmousemove=null;
document.onmouseup=null;
that.$refs.msgSpan.$parent.$parent.$parent.$el.style.webkitUserSelect='';//取消样式控制拖拽时禁止全选动作
that.$refs.msgSpan.$parent.$parent.$parent.$el.style.mozUserSelect='';//取消样式控制拖拽时禁止全选动作
};
};
},
CSS样式代码:
<style scoped>
.text {font-size: 14px;}
.space{height: 30px;width: 100%}
.item {padding: 0px 10px;color: #000;height: 30px;line-height: 30px;padding-left:15px;}
.box-card {position: fixed;bottom:;height: 200px;right: 20px;left: 250px;border-top:3px solid #ddd;z-index:;background: #eee;}
.msgbox-top{height: 30px;right:38px;background: #d6d6d6;border-bottom: 1px solid #ddd;z-index:;;cursor: n-resize;}
.msgbox-top h4{color:#000;font-size: 14px;line-height: 30px;padding-left: 10px;float: left;}
.msgbox-top>span{float:right;text-align: right;margin-right: 10px;line-height: 26px;height: 30px;}
.msgbox-top span>span{font-size: 14px;color: #00adff;cursor: pointer;margin-right: 20px;}
.msgbox-top span>span:hover{color:#10709e;}
.box-card span>i{float: right;line-height: 30px;color:#ff7b7b;}
.box-card span>i:hover{color:red;}
.msgbox-news{overflow-y: scroll;height: 170px;}
</style>