mouseX和mouseY仅检测对角线坐标

时间:2015-01-09 06:20:28

标签: javascript

我正在将输入框放置到mouseX和mouseY坐标上,但我的问题是当我点击时我只能点击身体上的一个小对角线区域。我想要它,以便我可以点击身体的任何地方,它将转到该位置。关于如何解决这个特殊问题的任何想法?

<body onclick = "getLocation(event)">
    <style>

html{
}
div{
    display: block;
}


 textarea, input {
      clear: both;
position: relative;
}
textarea, input {
overflow: auto;
width: 20%;
}
</style>

<input id = "enter" placeholder = "input" style = "top:20;left:40;"></input>
</body>
<script>
function getLocation(event){
var y = event.clientY;
var x = event.clientY;
console.log("Y:" + y + " X:" + x);
document.getElementById("enter").style.left = x;
document.getElementById("enter").style.top = y;
}
</script>

2 个答案:

答案 0 :(得分:0)

您需要设置正文的宽度和高度。您还需要在头寸上设置单位,并且您最有可能想要使用pageX和pageY,而不是clientX和clientY

&#13;
&#13;
function getLocation(event){
    var y = event.pageY;
    var x = event.pageX ;
    console.log("Y:" + y + " X:" + x);
    document.getElementById("enter").style.left = x + "px";
    document.getElementById("enter").style.top = y + "px";
  }

document.body.addEventListener("click", getLocation);
&#13;
html, body{
    width:100%;
    height:100%; 
}
div{
    display: block;
}
textarea, input {
    clear: both;
    position: relative;
}
textarea, input {
    overflow: auto;
    width: 20%;
}
&#13;
<input id="enter" placeholder="input" style="top:20px;left:40px;"></input>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<script>

function getLocation(event){

  document.getElementById('enter').style.left  = (window.Event) ? event.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
  document.getElementById('enter').style.top = (window.Event) ? event.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

}
</script>

只需替换它,它就有效:)