I have the following dummy html markup:
<table>
<body>
<tr>
<td id="cell" style="height: 1000px; width: 200px;"></td>
</tr>
</body>
</table>
I need to subscribe to click event on cell and get top offset relative parent table row (tr).
jQuery('#cell', function (e) {
// get top offset in pixels relative parent tr element
});
What's the best way?
Edit: I mean I need to get mouse click offset relative tr element
Assuming I correctly understood your question, this code should do the trick. It just outputs the x,y mouse coords relative to the cell container. The output alert is triggered by a mouse click on the cell.
o = $("#cell");
o.click(
function (e) {
offsetX = e.pageX - o.position().left;
offsetY = e.pageY - o.position().top;
alert('offsetX: ' + offsetX + '\noffsetY:' + offsetY);
}
);
Probably this..?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Documento senza titolo</title>
<style>
table{
border-collapse:collapse;
width:200px;
position:relative;
}
table tr{width:200px;float:left;background-color:red;position:relative;}
table tr td{width:100px;background-color:red;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//if you want offset from tr
$('td').click(function(){
var leftParent=$(this).parent('tr').offset().left
var topParent=$(this).parent('tr').offset().top
var left=Math.round(($(this).offset().left)-leftParent);
var top=Math.round(($(this).offset().top)-topParent)
alert('top'+top+' left'+left)
})
//if you want offset from table
$('td').click(function(){
var leftParent=$(this).parents('table').position().left
var topParent=$(this).parents('table').position().top
var left=Math.round(($(this).offset().left)-leftParent);
var top=Math.round(($(this).offset().top)-topParent)
alert('top'+top+' left'+left)
})
})
</script>
</head>
<body>
<table>
<tr>
<td class="cell">aaa</td>
<td class="cell">bbb</td>
</tr>
<tr>
<td class="cell">ccc</td>
<td class="cell">ddd</td>
</tr>
<tr>
<td class="cell">eee</td>
<td class="cell">fff</td>
</tr>
</table>
</body>
</html>
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.