I am trying to get the clicked x and y position on an image and wanted the image to stay at the same position as I scroll up/down. The problem is the scripts/browser didn't know what to do because the position of the image if fixed. I am guessing if I can change it to the absolute position and monitor it as I go but the scrolling thing is not that smooth at all. Any ideas guys?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#AutoScrollDotNetImage
{
width: 500px;
position: fixed;
clear: both;*/
}
body
{
background-color: Silver;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#DotNetImage").click(function (e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$('#posx').html('<p>X Coordinate: ' + x + ', Y Coordinate: ' + y + "</p><p>e.pageX: " + e.pageX + "e.pageY: " + e.pageY + "</p><p>" + "this.offsetLeft: " + this.offsetLeft + "this.offsetTop: " + this.offsetTop + "</p>");
});
});
</script>
</head>
<body>
<table width="100%">
<tr valign="top">
<td style="background-color: Gray"&g开发者_StackOverflow中文版t;
<div id="AutoScrollDotNetImage">
<p> ELEMENT COORDINATE</p>
<div id="posx">
<p> scroll and click on google image</p>
</div>
<img id="DotNetImage" alt="No change" src="http://www.google.com/images/logos/ps_logo2.png" />
</div>
</td>
<td>
<div style="clear: both; height: 5000px;">
</div>
</td>
</tr>
</table>
</body>
</html>
You need to include $('body').scrollLeft()
and $('body').scrollTop()
in your position equation:
$("#DotNetImage").click(function(e) {
var x = e.pageX - $('body').scrollLeft() - this.offsetLeft;
var y = e.pageY - $('body').scrollTop() - this.offsetTop;
// ...etc
}
See updated fiddle →
精彩评论