简体   繁体   中英

pageX and pageY with jQuery Keypress event not working

Here is my code, ev.pageX event is not working. I am not understanding why it so. But, its working with the click event. Event here used is the keypress event, I am looking for the value of ev.pageX so I could format the css absolute parameters according inside the text box.

Help needed!

<head>

    <style>
    textarea{
    width:300px;
    height:300px;  
    }

.popup{
    position:absolute; 
    border:1px solid gray;  
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>

<textarea></textarea>

<script>
    $(function() {
        var $popup = $('<select/>', {
            'html': 'popup'
        })
            .addClass('popup')
            .appendTo('body')
            .append($('<option/>').html('lala'), 
                    $('<option/>').html('blabla'))
            .change(function() {
                $(this).fadeOut();
            })
            .hide();



        $('textarea').keypress(function(ev) {               
            if ($popup.is(':visible')) {
                $popup.fadeOut();
            } else {
                if (ev.keyCode   === 32) {  
                    console.log('pressed');             

                    ev.preventDefault()
                    var pagex = ev.pageX;                             
                    console.log(pagex);

                    $popup.css({
                        'left': ev.pageX + 10,
                        'top': ev.pageY - 10
                    });


                    $popup.fadeIn();

                    console.log('working');
                }
                }                   


        });



    });
</script>
</body>

Your reference to ev is on a keypress event while pageX and pageY are reserved for mouse events.

You could potentially track the mouse coords on mouse move, assign the values to a global and then place your pop up at the last recorded global value. This however might be overly resource intense, depending o your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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