这期内容当中小编将会给大家带来有关使用JavaScript怎么实现拖拽图形伸缩效果,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
padding: 0;
margin:0;
}
.div1{
width: 200px;
height: 200px;
background-color: #71e4ff;
position: absolute;
top: 200px;
left: 200px;
}
.t,
.b{
width: 100%;
height: 20px;
background-color:#ffa2d3;
position: absolute;
}
.t{
left: 0;
top:0;
}
.b{
left: 0;
bottom:0;
}
.r,
.l{
width: 20px;
height: 100%;
background-color:#ffa2d3;
position: absolute;
}
.r{
right: 0;
top:0;
}
.l{
left: 0;
top:0;
}
.lt,
.lb,
.rt,
.rb{
width: 20px;
height: 20px;
background-color: #93ff6b;
position: absolute;
}
.lt{
left: 0;
top:0;
}
.rt{
right: 0;
top:0;
}
.lb{
left: 0;
bottom: 0;
}
.rb{
right: 0;
bottom:0;
}
</style>
</head>
<body>
<div class="div1" id="_div1">
<div class="t"></div>
<div class="r"></div>
<div class="b"></div>
<div class="l"></div>
<div class="lt"></div>
<div class="lb"></div>
<div class="rt"></div>
<div class="tb"></div>
</div>
</body>
</html>
<script>
// 获取元素
var _div1 = document.getElementById("_div1");
var divs = _div1.children;
// 遍历每个可以拖拽的元素
for(var i = 0;i < divs.length ;i++)
{
drag(divs[i]);
}
// 封装一个拖拽函数
function drag(obj){
obj.onmousedown = function(event){
// 捕获事件
var event = event || window.event;
// 存储当前的_div1的宽高
var divW = _div1.offsetWidth;
var divH = _div1.offsetHeight;
// 获得当前_div1的offsetLeft 和 offsetTop
var divL = _div1.offsetLeft;
var divT = _div1.offsetTop;
// 存储鼠标按下时的位置
var clientx = event.clientX;
var clienty = event.clientY;
document.onmousemove = function(event){
var event = event || window.event;
if(obj.className.indexOf('t') != -1){
_div1.style.height = divH + ( clienty- event.clientY) + 'px';
_div1.style.top = divT -( clienty- event.clientY)+ 'px';
}
if(obj.className.indexOf('b') != -1){
_div1.style.height = divH + ( event.clientY -clienty ) + 'px';
}
if(obj.className.indexOf('r')!= -1){
_div1.style.width = divW + ( event.clientX - clientx) + 'px';
}
if(obj.className.indexOf('l')!= -1){
_div1.style.width = divW + ( clientx - event.clientX) + 'px';
_div1.style.left = event.clientX + 'px';
}
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
}
return false;
}
</script>
上述就是小编为大家分享的使用JavaScript怎么实现拖拽图形伸缩效果了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注天达云行业资讯频道。