Vue页面实现全屏div拖动 禁用left后可只上下垂直拖动

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。Vue页面实现全屏div拖动 禁用left后可只上下垂直拖动,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

还是直接上代码

<template>
     <div class="main">
     <div ref="move_div" @touchstart="down" @touchmove="move" @touchend="end" :style="{top: top + 'px', left: left + 'px'}" class="drag_area"></div>
     </div>
</template>

export default {
     name: 'drag',
	     data () {
		     return {
			     flags: false,
			     position: {x: 0, y: 0, left: 0, top: 0},
			     top: 0,
			     left: 0,
			     width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
			     height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
		     }
	     },
     methods: {
	     down () { // 拖动开始的操作
		     this.flags = true
		     const refs = this.$refs.move_div.getBoundingClientRect()
		     let touch = event
		     if (event.touches) {
		     	touch = event.touches[0]
	     	 }
		     this.position.x = touch.clientX
		     this.position.y = touch.clientY
		     this.position.left = refs.left
		     this.position.top = refs.top
	     },
	     move () { // 拖动中的操作
		     if (this.flags) {
			     let touch = event
			     if (event.touches) {
			         touch = event.touches[0]
			     }
			     const xPum = this.position.left + touch.clientX - this.position.x
			     const yPum = this.position.top + touch.clientY - this.position.y
			     this.left = xPum
			     this.top = yPum
		     	this.banOut()
			     // 阻止页面的滑动默认事件
			     document.addEventListener('touchmove', function () {
			         event.preventDefault()
			     }, {passive: false})
	     	 }
	     },
	     end () { // 拖动结束的操作
		     this.flags = false
		     this.banOut()
	     },
	     banOut () { // 避免拖动出界的限制
		     const refs = this.$refs.move_div.getBoundingClientRect()
		     if (this.left < 0) {
		     	this.left = 0
		     } else if (this.left > this.width - refs.width) {
		     	this.left = this.width - refs.width
		     }
		     if (this.top < 0) {
		     	this.top = 0
		     } else if (this.top > this.height - refs.height) {
		     	this.top = this.height - refs.height
		     }
	     }
     }
}

<style lang="scss" scoped>
	.main{
	     background-color: brown;
	     height: -webkit-fill-available;
	     .drag_area{
	     width: 10vw;
	     height: 10vw;
	     background-color: dodgerblue;
	     position: absolute;
	     top: 0;
	     left: 0;
	}
</style>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/188064.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!