html拖动图片并缩放特效,原生JS实现图片拖拽移动与缩放.html

Document

#father {

width: 600px;

height: 500px;

background-color: rgb(226, 117, 184);

position: relative;

left: 200px;

top: 200px;

transform: scale(0.7201, 0.669);

}

#box {

width: 100px;

height: 100px;

background-color: aquamarine;

position: absolute;

}

img {

width: 100%;

height: 100%;

cursor: move;

}

#scale {

width: 10px;

height: 10px;

overflow: hidden;

cursor: se-resize;

position: absolute;

right: 0;

bottom: 0;

background-color: rgb(122, 191, 238);

}

test.jpg

// box是装图片的容器,fa是图片移动缩放的范围,scale是控制缩放的小图标

var box = document.getElementById("box");

var fa = document.getElementById('father');

var scale = document.getElementById("scale");

// 图片移动效果

box.onmousedown = function(ev) {

var oEvent = ev;

// 浏览器有一些图片的默认事件,这里要阻止

oEvent.preventDefault();

//alert(oEvent.clientX);

//alert(box.offsetLeft);

var disX = oEvent.clientX - box.offsetLeft;

var disY = oEvent.clientY - box.offsetTop;

fa.onmousemove = function(ev) {

oEvent = ev;

oEvent.preventDefault();

var x = oEvent.clientX - disX;

var y = oEvent.clientY - disY;

// 图形移动的边界判断

x = x <= 0 ? 0 : x;

x = x >= fa.offsetWidth - box.offsetWidth ? fa.offsetWidth - box.offsetWidth : x;

y = y <= 0 ? 0 : y;

y = y >= fa.offsetHeight - box.offsetHeight ? fa.offsetHeight - box.offsetHeight : y;

box.style.left = x + 'px';

box.style.top = y + 'px';

}

// 图形移出父盒子取消移动事件,防止移动过快触发鼠标移出事件,导致鼠标弹起事件失效

fa.onmouseleave = function() {

fa.onmousemove = null;

fa.onmouseup = null;

}

// 鼠标弹起后停止移动

fa.onmouseup = function() {

fa.onmousemove = null;

fa.onmouseup = null;

}

}

// 图片缩放效果

scale.onmousedown = function(e) {

// 阻止冒泡,避免缩放时触发移动事件

e.stopPropagation();

e.preventDefault();

var pos = {

'w': box.offsetWidth,

'h': box.offsetHeight,

'x': e.clientX,

'y': e.clientY

};

//alert(JSON.stringify(pos));

fa.onmousemove = function(ev) {

ev.preventDefault();

// 设置图片的最小缩放为30*30

var w = Math.max(30, ev.clientX - pos.x + pos.w)

var h = Math.max(30, ev.clientY - pos.y + pos.h)

// console.log(w,h)

// 设置图片的最大宽高

w = w >= fa.offsetWidth - box.offsetLeft ? fa.offsetWidth - box.offsetLeft : w

h = h >= fa.offsetHeight - box.offsetTop ? fa.offsetHeight - box.offsetTop : h

box.style.width = w + 'px';

box.style.height = h + 'px';

// console.log(box.offsetWidth,box.offsetHeight)

}

fa.onmouseleave = function() {

fa.onmousemove = null;

fa.onmouseup = null;

}

fa.onmouseup = function() {

fa.onmousemove = null;

fa.onmouseup = null;

}

}

一键复制

编辑

Web IDE

原始数据

按行查看

历史

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值