创建一个新的div并将其显示在页面上鼠标光标所在的位置

时间:2014-08-14 16:03:04

标签: javascript jquery html

目前,圈子被添加到html标记中的<p> 您可以在下面看到我是如何做到这一点的。

但我真正想要的是创建div,鼠标光标在页面上 我如何获得光标的位置并在那里创建一个div?

感谢。

var count = 0;
/*
 * Function(makeLetters)
 * Removes first character in text box.
 * Creates circle Letters using first character.
 */
$(document).click(function (makeLetters) {
    //Get characters currently entered into textbox
    var letters = $('#letters').val();
    //Take the firstLetter only
    var firstLetter = letters.substr(0, 1);
    //Count how many characters currently entered
    var numberOfLetters = letters.length;
    //Use length of entry to take all characters except first
    var restOfLetters = letters.substr(1, numberOfLetters);
    //All characters except first set as textbox entry
    $("#letters").val(restOfLetters);
    //Check that there is a first character
    if (firstLetter != "") {
        count++;
        //Create a new circle letter by inserting new div class
        $("p").append('<div class="circle' + count + '" style="border-radius: 50%;width:    36px;height:36px;padding:8px;background:#FF7D5C;color:black;text-align:center;font:32px Arial, sans-serif;display:inline-block;margin-right:4px;margin-bottom:4px;">' + firstLetter.toUpperCase() + '</div>');
        $("p").children().last().hide().fadeIn();
    }
});

2 个答案:

答案 0 :(得分:1)

据我所知,你不能单独获得鼠标位置,但你可以使用jQuery来监听mousemove事件并将位置存储在变量中以供以后使用:

var mousePosition = { x: 0, y: 0 };

$(document).mousemove(function(e) {
    mousePosition.x = e.pageX;
    mousePosition.y = e.pageY;
});

然后,您需要使用postion: [absolute/fixed];根据mousePosition定位div。

答案 1 :(得分:1)

你是通过从事件中获取鼠标位置来做到这一点的,你出于某种奇怪的原因命名为makeLetters

$(document).click(function(event) {

    var letters         = $('#letters').val();
    var firstLetter     = letters.substr(0, 1);
    var numberOfLetters = letters.length;
    var restOfLetters   = letters.substr(1, numberOfLetters);
    var mouseLeft       = event.pageX;
    var mouseTop        = event.pageY;

    $("#letters").val(restOfLetters);

    if (firstLetter != "") {
        count++;

        var div = $('<div />', {
            'class' : 'circle' + count,
            text  : firstLetter.toUpperCase(),
            css : {
                 position: 'fixed',
                 top     : mouseTop + 'px',
                 left    : mouseLeft + 'px', 
                 display : 'none'
                 // ... the rest of the styles here

            }
        });

        $("p").append( div.fadeIn() );
    }
});