如何在JavaScript中点击事件添加圈子?

时间:2017-03-28 23:07:03

标签: javascript jquery

你能告诉我如何在JavaScript中点击事件添加圈子吗?实际上,我希望实现这一点,如果用户点击div元素中的任意位置,它会在该位置添加圆圈。目前,它添加未添加到正确位置的任何位置。应该在用户点击的地方添加。

This是我的代码。

$(function(){
  $('#fx').click(function(e){
    var circle=$('<div class="circle"></div>');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});

3 个答案:

答案 0 :(得分:1)

您必须更改以下代码行:

circle.css('top', e.pageY);

答案 1 :(得分:1)

如果您希望圆圈准确地从您单击的位置开始,则顶部应为e.pageY

然后你必须否定(r)将它指向原点。由于圆的半径为15px,因此转换为

circle.css('top',e.pageY - 15);
circle.css('left',e.pageX - 15)

<强> plunker

答案 2 :(得分:1)

如果您希望圈子定位完全,则用户点击...

你必须知道pageXpageY没有给你鼠标箭头“尖端”的位置......但是显示鼠标图标的中心。

所以,“通常的图标”尺寸是20px x 20px。

我已更新您的Plunker 我添加了一个“点”来显示用户希望它作为中心的确切位置,这是箭头的尖端。

我把圈子做得更大,以确保中间。

自己看看forked and updated Plunker

代码是:

$(function(){
  $('#fx').click(function(e){

    var width = 300;        // Width of the element has to be hard coded here;
    var radius = width/2;
    console.log(radius);    // Since element is a circle, the radius is enought to set position.

    var mouseTip = 10;      // But mouse arrow tip has to be taken in account.

    var circle=$('<div class="circle"></div>');
      circle.css('top',e.pageY-radius-mouseTip);
      circle.css('left',e.pageX-radius-mouseTip);
      $('#fx').append(circle);

    var dot=$('<div class="dot"></div>');       // This is only intended to show where user REALLY wants to clic
                                                // and the FACT that there is a correction to apply.
      dot.css('top',e.pageY-mouseTip);
      dot.css('left',e.pageX-mouseTip);
      $('#fx').append(dot);
  });
});

所以这对于“箭头”默认光标来说很棒,如果你使用“指针”图标,它将需要另一个鼠标校正值。