template:
<div
v-drag
class="new-sir-kf"
ref="newSirKF"
@click="toggleOpenKf"
>
</div>
style:
.new-sir-kf {
display: inline-block;
width: 76px;
height: 111px;
position: fixed;
bottom: 5%;
left: 2px;
z-index: 99999;
cursor: pointer;
//background-image: url("../common/images/newsir.png");
background:green;
background-size: cover;
text-align: center;
&::before {
display: none;
content: "智能问答";
width: 80%;
background: black;
color: white;
padding: 2px 4px;
border-radius: 4px;
position: absolute;
top: 60%;
left: 6%;
animation: up-in 0.28s linear;
}
&:hover::before {
display: inline-block;
}
&[draging-flag="true"] {
&::after {
content: " ";
position: fixed;
z-index: 99999;
width: 100%;
height: 100%;
left: 0;
top: 0;
}
}
}
main.js文件:
Vue.directive('drag', {
//1.指令绑定到元素上回立刻执行bind函数,只执行一次
//2.每个函数中第一个参数永远是el,表示绑定指令的元素,el参数是原生js对象
//3.通过el.focus()是无法获取焦点的,因为只有插入DOM后才生效
bind: function(el) {},
//inserted表示一个元素,插入到DOM中会执行inserted函数,只触发一次
inserted: function(el) {
let odiv = el; //获取当前元素
let firstTime = '',
lastTime = '';
let topPx = 0;
console.log(el)
// return
if (el.classList[0] === 'content-box') {
topPx = 300
} else {
topPx = 0
}
el.onmousedown = function(e) {
var disx = e.pageX - el.offsetLeft;
var disy = e.pageY - el.offsetTop;
odiv.setAttribute('data-flag', false)
odiv.setAttribute('draging-flag', true)
firstTime = new Date().getTime();
document.onmousemove = function(e) {
console.log('上边距', e.pageY - disy)
if (topPx) {
/* 控制IT支持拖拽 */
if (e.pageY - disy < 3) {
el.style.top = 3 + topPx + 'px';
} else {
el.style.top = e.pageY - disy + topPx + 'px';
}
/* end */
} else {
el.style.top = e.pageY - disy + 'px';
}
el.style.left = e.pageX - disx + 'px';
};
document.onmouseup = function(event) {
document.onmousemove = document.onmouseup = null;
lastTime = new Date().getTime();
if ((lastTime - firstTime) > 200) {
odiv.setAttribute('data-flag', true)
event.stopPropagation()
}
setTimeout(function() {
odiv.setAttribute('draging-flag', false)
}, 100)
}
}
}
})
methods:
// newsir 客户问答点击事件
toggleOpenKf(e) {
if (this.isMessage) return;
let isDrag = false;
try {
isDrag = e.target.getAttribute("data-flag") === "true";
} catch (e) {}
if (isDrag) {
return;
}
// 再去真正调用这个div的点击事件
this.$refs.SmartQA.open();
},