此代码适用于Firefox和IE,但不适用于Chrome或Safari(请尝试点击第16页)。
问:如何让它在Chrome或Safari中运行?
<!DOCTYPE html>
<title>getOffset</title>
<style type="text/css">
table{border:none;width:10000px;position:absolute}
td{width:1000px;height:1000px;border:2px solid}
#the_input{width:100px;height:100px;background:#f00;position:absolute}
</style>
<script>
onload = function(){
var all_td = document.getElementsByTagName('td');
function getOffset( el ) {
var _x = 0,
_y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
for(var i = 0, len = all_td.length; i < len; i++) {
all_td[i].onclick = function () {
var x = getOffset(this).left,
y = getOffset(this).top;
alert(x + ' x ' + y);
}
}
}
</script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
<tr>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
</tr>
</table>
<input id=the_input value="some text">
答案 0 :(得分:1)
只需将getOffset
的代码更改为
function getOffset( el ) {
var _x = 0,
_y = 0;
while( el && el.tagName.toLowerCase() != 'body' && !isNaN( el.offsetLeft ) && !isNaN(el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
当我在chrome中调试时,它采用BODY
元素的scrollLeft和scrollLeft值,而在IE和FF上它是0
。