我有以下虚拟html标记:
<table>
<body>
<tr>
<td id="cell" style="height: 1000px; width: 200px;"></td>
</tr>
</body>
</table>
我需要订阅单击单元格上的事件并获取顶部偏移量相对父表行(tr)。
jQuery('#cell', function (e) {
// get top offset in pixels relative parent tr element
});
最好的办法是什么?
编辑:,我的意思是我需要鼠标单击偏移相对tr元素
发布于 2014-03-20 16:30:20
假设我正确地理解了你的问题,这段代码就能做到这一点。它只输出相对于单元容器的x,y鼠标坐标。输出警报是由鼠标单击单元格触发的。
o = $("#cell");
o.click(
function (e) {
offsetX = e.pageX - o.position().left;
offsetY = e.pageY - o.position().top;
alert('offsetX: ' + offsetX + '\noffsetY:' + offsetY);
}
);
http://jsfiddle.net/Dcudb/1/
发布于 2014-03-20 17:10:00
可能是这个..?
<!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>
https://stackoverflow.com/questions/22538417
复制相似问题