人工手绘很难做到控制,所以可以另辟蹊跷,比如:
1、正方形改由点击按钮生成,正方形的宽高就是固定的,或某一个可自定义的值。这样就可以多次生成,生成的大小也都是一样的
2、绘制好正方形可以选择,选择后进行复制粘贴,这样也能做到
这两种都需要正方形可以拖拽移动
重新写了个,没有图片,用一个黑色背景的div代替的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.myImg{
height:100%;width:100%;
position: absolute;
z-index:0;margin-left:0px;margin-top:0px;
border:1px solid #ccc;
background: #000;
}
#h-coverImg{
position: relative;
z-index:1;
width: 720px;
height: 576px;
background-size: 100%;
overflow: hidden;
}
#h-coverImg .box{
position: absolute;
border: 2px solid #f00;
cursor: move;
top: 0px; left: 0px;
color: red;
font-size: 14px;
font-weight: bold;
}
#h-coverImg .box:hover{
background: rgba(255, 0, 0, .4);
}
</style>
<body>
<p>
宽高:<input type="text" id="box-width" value="100"/>
<button id="creatBtn">creat box</button>
</p>
<div id="h-coverImg">
<div class="myImg"></div>
</div>
</body>
<!--<script language="javascript" type="text/javascript" src="../js/jquery-2.1.1.min.js"></script>-->
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
$('#creatBtn').on('click', function(){
var val = $('#box-width').val()
console.log(val)
if(!val){
return alert('请输入元素宽高')
}
if(isNaN(val)){
return alert('元素宽高应该是一个数字')
}
creatEle( Number(val) )
})
var count = 0
function creatEle(width){
var $box = $('<div class="box"></div>')
$box.css({
width: width,
height: width
}).html(++count).wmDrag();
$('#h-coverImg').append($box)
}
$.fn.wmDrag = function(){
return this.each(function(index, oDiv){
oDiv.draggable = false
oDiv.style.cursor = 'move'
oDiv.onmousedown = function (e) {
if(e.button == 2)return; //过滤右键按下事件
var omousemove = document.onmousemove,
omouseup = document.onmouseup;
//鼠标按下,计算当前元素距离可视区的距离
var disX = e.clientX,
disY = e.clientY,
sty = window.getComputedStyle(oDiv),
transition = sty.transition,
left = parseInt(sty.left),
top = parseInt(sty.top),
$parent = $(oDiv).parent(),
//maxL = document.body.clientWidth - parseInt(sty.width),
maxL = $parent.width() - parseInt(sty.width),
//maxT = document.body.clientHeight - parseInt(sty.height);
maxT = $parent.height() - parseInt(sty.height);
oDiv.style.transition = 'none'
oDiv.style.left = left + 'px'
oDiv.style.top = top + 'px'
oDiv.style.bottom = oDiv.style.right = 'auto'
document.onmousemove = function (e) {
//通过事件委托,计算移动的距离
var l = e.clientX - disX;
var t = e.clientY - disY;
l = left + l
l = l > maxL ? maxL : l < 0 ? 0 : l
t = top + t
t = t > maxT ? maxT : t < 0 ? 0 : t
//移动当前元素
oDiv.style.left = l + 'px';
oDiv.style.top = t + 'px';
};
document.onmouseup = function (e) {
document.onmousemove = omousemove;
document.onmouseup = omouseup;
oDiv.style.transition = transition
};
};
})
}
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…