今天要分享的是运用原生JS拖拽进度条改变元素大小,效果如下:
以下是代码实现,欢迎大家复制粘贴。
代码语言:javascript复制<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS拖拽进度条改变元素大小</title>
<style>
#parent {
width: 400px;
height: 20px;
background: #CCC;
position: relative;
margin: 20px auto;
}
#div1 {
width: 20px;
height: 20px;
background: red;
cursor: pointer;
position: absolute;
}
#div2 {
width: 0px;
height: 0px;
margin: 0 auto;
background: yellow;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var oParent = document.getElementById('parent');
var oDiv2 = document.getElementById('div2');
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
//计算鼠标相对滑块上的位置
var disX = oEvent.clientX - oDiv.offsetLeft;
document.onmousemove = function (ev) {
var oEvent = ev || event;
//计算滑块的动态left值
var l = oEvent.clientX - disX;
//限制拖拽范围
if (l < 0) {
l = 0;
} else if (l > oParent.offsetWidth - oDiv.offsetWidth) {
l = oParent.offsetWidth - oDiv.offsetWidth;
}
oDiv.style.left = l 'px';
//计算拖拽移动距离与可拖动总范围的比例
var scale = l / (oParent.offsetWidth - oDiv.offsetWidth);
//让Div2跟随鼠标拖动放大与缩小
oDiv2.style.width = scale * 300 'px';
oDiv2.style.height = scale * 300 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="parent">
<div id="div1"></div>
</div>
<div id="div2"></div>
</body>
</html>