鼠标光标在图像上的坐标:Y坐标不是整数!怎么会这样?

时间:2012-06-28 13:21:48

标签: javascript jquery

感谢我收到here的建议,我修复了代码的一些问题,现在我有了:

window.onload = function(){

    var tooltip = $( '<div id="tooltip">' ).appendTo( 'body' )[0];

$( 'img' ).
    each(function () {
        var pos = $( this ).position(),
            top = pos.top,
            left = pos.left,
            width = $( this ).width(),
            height = $( this ).height(); 
        $( this ).
            mousemove(function ( e ) {
                var x = e.pageX - left,
                    y = e.pageY - top;

                $( tooltip ).html( 'x = ' + x + '<br/>y = ' + y ).css({
                    left: e.clientX + 10,
                    top: e.clientY + 10
                }).show();
            }).
            mouseleave(function () {
                $( tooltip ).hide();
            }); 

    });

};

不幸的是,Y坐标不是整数!见图:

enter image description here

差异与应该是什么不变:-0.42。它从照片上边缘的-0.42到下边缘的1198.58变化。 (图片高度为1200)。

我绝对可以解决这个问题,但这不是一个干净的解决方案。我想从一开始就把它弄好。

这是CSS:

body { font:13px/1.4 Arial, sans-serif; margin:50px; background:gray; }
#tooltip { text-align:left; background:black; color:white; padding:3px 0; position:fixed; display:none; white-space:nowrap; }

这是HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script></head>
</head>

<body>


<div id="content">
<h1>JS test</h1>
<img class="coords" src = "pic.jpg">

<p>Paragraph between images</p>


<img class="coords" src = "pic.jpg">
</div>

</body>
</html

非常感谢你的帮助!

的Davide

1 个答案:

答案 0 :(得分:3)

回答标题中的问题:CSS中的Top或Left可以定义为百分比或'em'等。然而jQuery总是返回像素,所以这可能是获取浮点数而不是整数时的原因jQuery转换为例如百分比到像素。

第二个问题,为什么它总是-0.42,我不确定没有jsFiddle或类似的东西。 编辑:但您使用的是.position(),它给出了相对于的位置,而e.pageX则相对于。因此,e.pageY在图像的顶部可以是0.42(相对于页面的顶部),而image.position()。top可以是0(相对于父级),因此得到的x变为-0.42。

您可能想要使用相对于页面的.offset()!见http://api.jquery.com/offset/