#design{
position: fixed;
width: auto;
height: auto;
width: 15rem;
min-width: 15rem;
min-height: 30rem;
max-width: 70%;
max-height: 90%;
top: calc(50% - 15rem);
left: calc(100% - 15rem);
z-index: 99999;
background-color: #fafafa;
cursor: pointer;
}
<div id="design" style=""></div>
$(document).ready(function() {
var div = document.getElementById("design");
div.onmousedown = function() {
var clientX_ = -1;
var clientY_ = -1;
var is = false;
div.onmousemove = function(e) {
var evt = e || event;
if (is) {
var x = $("#design").css("left");
x = x.substring(0, x.length - 2);
x = Number(x);
x=x + evt.clientX - clientX_;
if(x>0){
var width_=(Number($("#design").css("width").substring(0,$("#design").css("width").length-2))/2);
if((document.body.clientWidth-width_)>=(x+width_)){
$("#design").css("left", x + 'px');
}
}
var y = $("#design").css("top");
y = y.substring(0, y.length - 2);
y = Number(y);
y=y + evt.clientY - clientY_;
if(y>0){
var height_=(Number($("#design").css("height").substring(0,$("#design").css("height").length-2))/2);
if((document.body.clientHeight-height_)>=(y+height_)){
$("#design").css("top", y + 'px');
}
}
}
is = true;
clientX_ = evt.clientX;
clientY_ = evt.clientY;
};
div.onmouseout=function() {
div.onmousemove = null;
};
div.onmouseup = function() {
div.onmousemove = null;
};
};
});
document.body.clientWidth,document.body.clientHeight约束div的位置
全部代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
html,body,.all{
width: 100%;
height: 100%;
}
#design{
position: fixed;
width: auto;
height: auto;
width: 15rem;
min-width: 15rem;
min-height: 30rem;
max-width: 70%;
max-height: 90%;
top: calc(50% - 15rem);
left: calc(100% - 15rem);
z-index: 99999;
background-color: #eee;
cursor: pointer;
}
</style>
<script type="application/javascript" src="public/js/jquery-1.8.0.min.js"></script>
</head>
<body >
<div id="design" style="">
</div>
<script>
$(document).ready(function() {
var div = document.getElementById("design");
div.onmousedown = function() {
var clientX_ = -1;
var clientY_ = -1;
var is = false;
div.onmousemove = function(e) {
var evt = e || event;
if (is) {
var x = $("#design").css("left");
x = x.substring(0, x.length - 2);
x = Number(x);
x=x + evt.clientX - clientX_;
if(x>0){
var width_=(Number($("#design").css("width").substring(0,$("#design").css("width").length-2))/2);
if((document.body.clientWidth-width_)>=(x+width_)){
$("#design").css("left", x + 'px');
}
}
var y = $("#design").css("top");
y = y.substring(0, y.length - 2);
y = Number(y);
y=y + evt.clientY - clientY_;
if(y>0){
var height_=(Number($("#design").css("height").substring(0,$("#design").css("height").length-2))/2);
if((document.body.clientHeight-height_)>=(y+height_)){
$("#design").css("top", y + 'px');
}
}
}
is = true;
clientX_ = evt.clientX;
clientY_ = evt.clientY;
};
div.onmouseout=function() {
div.onmousemove = null;
};
div.onmouseup = function() {
div.onmousemove = null;
};
};
});
</script>
</body>
</html>