效果
预览
预览地址:http://120.79.163.94/JYeontuComponents/#/JHoverBtnView
关键代码实现
阻止默认拖动选择事件
preventEvent(){
document.getElementById('j-hover-btn').ondragstart = function() {
return false;
};
document.getElementById('j-hover-btn').onselectstart = function () {
return false;
};
},
鼠标点击按钮事件
itemClick(event){
//记录点击的初始位置
this.startX = event.pageX - window.scrollX;
this.startY = event.pageY - window.scrollY;
//修改点击状态
this.clickStatus = true;
//阻止默认选中事件
this.windowPreventEvent();
}
鼠标移动事件
handleMouseover(event){
//按钮处于点击状态
if(this.clickStatus){
//按钮为fixed布局,位置需要减去窗口滚动偏移量
const endX = event.pageX - window.scrollX,
endY = event.pageY - window.scrollY;
const dom = document.getElementById('j-hover-btn');
//区分点击事件和拖动事件
if(Math.abs(endX - this.startX) > this.clickDis || Math.abs(endY - this.startY) > this.clickDis){
this.isClick = false;
}
//移动按钮位置
dom.style.left = endX - this.width / 2 + 'px';
dom.style.top = endY - this.width / 2 + 'px';
}
}
鼠标抬起事件
handleMouseup(event){
if(this.clickStatus){
const endX = event.pageX - window.scrollX,
endY = event.pageY - window.scrollY;
if(this.isClick){
//父组件回调事件
this.$emit('hoverBtnClick');
}else{
if(!this.autoHide) return;
//按钮贴边自动缩进隐藏
const width = document.body.offsetWidth;
const height = document.body.offsetHeight;
const dom = document.getElementById('j-hover-btn');
if(endX < this.width / 2){
dom.style.left = -(this.width - this.showWidth) + 'px';
}else if(endX > width - this.width / 2){
dom.style.left = width - this.showWidth + 'px';
}
}
//恢复状态
this.clickStatus = false;
this.isClick = true;
this.windowPreventEventCancel();
}
}
npm引入
组件以上传到npm,可以直接install使用,0.1.4以上版本加入了该组件。
1.安装
npm i @jyeontu/jvuewheel -S
2.引入
//引入组件库
import jvuewheel from '@jyeontu/jvuewheel'
//引入样式
import '@jyeontu/jvuewheel/lib/jvuewhell.css'
Vue.use(jvuewheel);
3.vue中引用组件
<j-hover-btn bgColor = 'pink'
width = '80'
text = '按钮文字'
:btn-style = "btnStyle"
@hoverBtnClick = "hoverBtnClick()">
</j-hover-btn>
资源地址
组件使用文档
文档地址:http://120.79.163.94/JYeontuComponents/#/homePage
代码地址
Gitee地址:https://gitee.com/zheng_yongtao/jyeontu-component-warehouse/tree/master/JYeontuComponentWarehouse
说在后面
标签:vue,const,endX,拖拽,width,window,按钮,document,event From: https://blog.51cto.com/u_16148374/6993516