简体   繁体   English

Onclick在带有javascript坐标的主体更改div位置

[英]Onclick in body change div position with javascript coordinates

i just want to change div position onclick, when i click in the body i want div to appear there. 我只想更改div的位置onclick,当我在正文中单击时希望div出现在此处。

#elem{
    width: 100px;
    height: 100px;
    border: 1px solid red;
    position: absolute;
    top: 0;
    left: 150px;

}

var elem = document.getElementById("elem");
elem.onclick = funct;


function funct( event ){

     var x = event.clientX;
     var y = event.clientY;
        this.style.top = y + 'px';
        this.style.left = x + 'px';
}

Here's the working example. 这是工作示例。 You need to add event listener to document/body element: 您需要将事件监听器添加到document / body元素:

 var target = document.getElementById('target'); document.addEventListener('click', function (e) { target.style.left = e.clientX + 'px'; target.style.top = e.clientY + 'px'; }); 
 #target { width: 50px; height: 50px; background-color: #ccc; position: absolute; } 
 <div id="target"></div> 

You can expand the handler further and center the div on the cursor position as well: 您可以进一步扩展处理程序并将div置于光标位置的中心:

 var target = document.getElementById('target'); document.addEventListener('click', function (e) { target.style.left = e.clientX - target.offsetWidth / 2 + 'px'; target.style.top = e.clientY - target.offsetHeight / 2 + 'px'; }); 
 #target { width: 50px; height: 50px; background-color: #ccc; position: absolute; } 
 <div id="target"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM