如何在jquery中使用.hover事件获取html中的坐标? [英] How to get the coordinates in html using .hover event in jquery?

查看:107
本文介绍了如何在jquery中使用.hover事件获取html中的坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都可以帮助我如何创建包含x y坐标的工具提示吗?这是我的示例代码:

Can everybody help me on how to create a tooltip that contain the x y coordinates? Here is my sample code:

    <style type="text/css">
        a img {
            border: 3px solid blue;
        }

        #largeImage {
            position: absolute;
            padding: .5em;
            background: #e3e3e3;
            border: 1px solid #bfbfbf;
        }
    </style>

    <script type="text/javascript">
        $(function() {
            var offsetX = 20;
            var offsetY = 10;

            $('a').hover(function(e) {
                var href = $(this).attr('href');

                var x = e.pageX - this.offsetLeft;
                var y = e.pageY - this.offsetTop;

                $('<div id="largeImage">' + 'X: ' + x + ' Y: ' + y + '</div>')
                .css('top', e.pageY + offsetY)
                .css('left', e.pageX + offsetX)
                .appendTo('body');
            }, function() {
                $('#largeImage').remove();
            });

            $('a').mousemove(function(e) {
                $('#largeImage')
                .css('top', e.pageY + offsetY)
                .css('left', e.pageX + offsetX);
            });
        });
    </script>

<body>
    <a href="Images/FredLarge.jpg">
        <img src="Images/FredSmall.jpg" alt="squidward" />
    </a>
</body>

在此示例中发生的是坐标没有改变.尽管它获取坐标,但它不会改变.

What happened in this example is that the coordinates aren't changing. Although it gets the coordinates but it doesn't change.

*此代码实际上就像是图像的工具提示,因此只需忽略ID名称即可.

*This code is actually like a tooltip of image, so just ignore the id name.

推荐答案

hover不会连续触发.当您移开时它只会触发一次,而当您移出时它只会触发一次.这就是为什么它不随鼠标移动的原因.尝试绑定到 mousemove . jQuery文档甚至有一个将鼠标悬停在正方形上并显示坐标的示例.

hover does not fire continuously. It only fires once when you move over and once when you move out. So that is why it doesn't move with the mouse. Try binding to mousemove instead. The jQuery docs even have an example of mousing over a square and displaying the coordinates.

这篇关于如何在jquery中使用.hover事件获取html中的坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆