2015-11-25 66 views
-3

我希望它创建鼠标所在的div。我有以下代码:在div中的div位置

var mouseisdown = false; 

$(document).mousedown(function(event) { 
mouseisdown = true; 
doSomething(); 
}).mouseup(function(event) { 
mouseisdown = false; 
}); 

function doSomething(e){ 
    var draw = document.createElement("div"); 
    draw.className = "draw"; 
    document.body.appendChild(draw); 
    draw.style.top = e.clientY + "px"; 
    draw.style.left = e.clientX + "px"; 
if (mouseisdown) 
    doSomething(); 
} 
+1

的[jQuery的创建上点击鼠标的div(http://stackoverflow.com/questions/19642277/jquery-create-div-on-mouseclick) – sdespont

+0

你可能要考虑可能的复制[使用mousemove](http://jsfiddle.net/jv9e9qtd/)来代替。 – Stryner

回答

1

基本上你已经知道答案,但是你过于复杂吧:

  • 取出mouseisdown变量和事件侦听器
  • 添加doSomething作为click事件侦听
  • 递归调用doSomething

$(document).click(function doSomething(e){ 
 
    var draw = document.createElement("div"); 
 
    draw.className = "draw"; 
 
    document.body.appendChild(draw); 
 
    draw.style.top = e.clientY + "px"; 
 
    draw.style.left = e.clientX + "px"; 
 
});
.draw { 
 
    position: absolute; 
 
    height: 10px; 
 
    width: 10px; 
 
    margin: -5px; 
 
    background: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Click somewhere