Vue缩放指令v-resize

Vue封装自定义全局指令,等比例缩放dom元素,可更改resizeDomMove()进行宽增加或者高增加

  1. vue自定义全局指令
Vue.directive('resize', {
	inserted: function (el) {
		let resizeable = false,
			minW = '400', minH = '225',
			val, clientX, clientY
		el.addEventListener('mousedown', resizeMove)
		document.addEventListener('mousemove', resizeDomMove)
		document.addEventListener('mouseup', resizeDomUp)
		function getAddress(ev) {
			let xPos1, yPos1, xPos2, yPos2, offset, cls;
			cls = '';

			// xPos2 = ev.offsetX;
			// yPos2 = ev.offsetY;


			yPos1 = ev.clientY;
			xPos1 = ev.clientX;

			offset = 10;
			// console.log(el.offsetHeight, el.getBoundingClientRect().top, el.offsetHeight + el.getBoundingClientRect().top)
			// console.log(yPos1)

			// if (yPos2 < offset) cls += 'n';
			if (yPos1 > el.offsetHeight + el.getBoundingClientRect().top - offset) cls += 's';
			// if (xPos2 < offset) cls += 'w';
			if (xPos1 > el.offsetWidth + el.getBoundingClientRect().left - offset) cls += 'e';

			return cls;
		}
		function resizeMove(e) {
			e.stopPropagation()
			let d = getAddress(e)
			if (d !== '') {
				resizeable = true
				val = d
				clientX = e.clientX
				clientY = e.clientY
			}
		}
		function resizeDomMove(e) {
			let d = getAddress(e)
			let cursor
			if (d === '') cursor = 'default';
			else if (d === 'se') { cursor = d + '-resize' };
			el.style.cursor = cursor;
			if (resizeable) {
				if (val == 'se') {
					// 等比例缩放
					el.style.width = Math.max(minW, el.offsetWidth + (e.clientY - clientY)) + 'px'
					el.style.height = Math.max(minH, el.offsetHeight + ((e.clientY - clientY) * 0.5625)) + 'px'
					clientX = e.clientX
					clientY = e.clientY
				}
			}
		}
		function resizeDomUp(e) {
			resizeable = false
		}
	}
})
  1. 组件中使用
<div class="content" v-resize></div>
Logo

前往低代码交流专区

更多推荐