用js实现鼠标的拖拽,并且双击变大铺满全屏,再双击返回原来大小。
效果图:
双击变大后效果:
HTML代码:
<div id="bigbox">
<div id="smallbox">拖拽区域</div>
</div>
CSS样式:
*{
margin: 0;
padding: 0;
}
#bigbox {
width: 300px;
height: 300px;
background-color: cadetblue;
position: absolute;
border: 1px solid gray;
}
#smallbox {
width: 100%;
height: 30px;
border: 1px solid gray;
cursor: move; //让鼠标样式变为移动样式
text-align: center;
}
JavaScript代码:
let bigbox = document.getElementById("bigbox");
let smallbox = document.getElementById("smallbox");
//以上代码是获取拿到元素
smallbox.onmousedown = function (evt) {
let e = evt || event;
let offX = e.offsetX;
let offY = e.offsetY;
document.onmousemove = function (evt) {
let e = evt || event;
let left = e.pageX - offX;
let top = e.pageY - offY;
if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}
let maxleft = innerWidth - bigbox.offsetWidth;
if (left > maxleft) {
left = maxleft;
}
let maxtop = innerHeight - bigbox.offsetHeight;
if (top > maxtop) {
top = maxtop;
}
bigbox.style.left = left + "px";
bigbox.style.top = top + "px";
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
//以上代码是鼠标拖拽且拖拽时不能超出window边框效果代码
let _left;
let _top;
let flog = true;
smallbox.ondblclick = function (evt) {
let e = evt || event;
if (flog) {
_left = e.pageX - e.offsetX;
_top = e.pageY - e.offsetY;
bigbox.style.width = window.innerWidth + "px";
bigbox.style.height = window.innerHeight + "px";
bigbox.style.left = 0;
bigbox.style.top = 0;
flog = false;
}else{
bigbox.style.width = 300 + "px";
bigbox.style.height = 300 + "px";
flog = true;
bigbox.style.left = _left + "px";
bigbox.style.top = _top + "px";
}
}
//以上代码为双击变大变小效果代码