背景
在项目中偶然碰到,添加图片自定义改变大小进行排版
原理
初始状态:
鼠标在右下角拖动时:
代码如下:
<style>
#div1{
width:200px;
height:200px;
background-color: red;
position:relative;
top:50%;
left:50%;
}
#div2{
width:10px;
height:10px;
background-color: black;
position:absolute;
right:0;
bottom:0;
}
</style>
<body>
<div id="div1">
<div id="div2" @mousedown="dragToChangeImg"></div>
</div>
<script>
var oDiv=document.getElementById('div1');
var oDiv2=document.getElementById('div2');
function dragToChangeImg(ev){
ev=ev||event;
var disX=ev.clientX-oDiv2.offsetLeft;
var disY=ev.clientY-oDiv2.offsetTop;
document.onmousemove=function (ev){
ev=ev||event;
oDiv.style.width=ev.clientX-disX+oDiv2.offsetWidth+'px';
oDiv.style.height=ev.clientY-disY+oDiv2.offsetHeight+'px';
}
document.onmouseup=function (){
document.onmousemove = document.onmouseup = null;
}
}
</script>
</body>
结语
日常记录小功能,大家如果觉得小黑块难看,可以将它换成一张小图片,我在这里只是为了做出简单的效果哈。…^-^ (前端小白,如有错误,欢迎指正~~)