最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - offsetParent.scrollTop doesn't work in most browsers - Stack Overflow

programmeradmin2浏览0评论

Am I doing something wrong? It looks like this only works in IE, though I can't see what I'm expecting that others can't handle.

<div id="test" style="height:4em;overflow:scroll;">
one<br />two<br />three<br />four<br />five<br />six<br />seven<br />eight<br />nine<br />ten<br />
<b id="item1">I should e into view!</b>
</div>
<script><!--
document.getElementById("item1").offsetParent.scrollTop=1000;
//--></script>

(please don't answer why don't you use "test", because this is a simplified example to demonstrate I have an issue using offsetParent)

Am I doing something wrong? It looks like this only works in IE, though I can't see what I'm expecting that others can't handle.

<div id="test" style="height:4em;overflow:scroll;">
one<br />two<br />three<br />four<br />five<br />six<br />seven<br />eight<br />nine<br />ten<br />
<b id="item1">I should e into view!</b>
</div>
<script><!--
document.getElementById("item1").offsetParent.scrollTop=1000;
//--></script>

(please don't answer why don't you use "test", because this is a simplified example to demonstrate I have an issue using offsetParent)

Share Improve this question asked Dec 21, 2011 at 20:11 Stijn SandersStijn Sanders 36.8k11 gold badges47 silver badges70 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Just reading the documentation on offsetParent and looking at what happens in Chrome and Firefox, it's pretty clear that offsetParent is being set to the <body> element and your div with id="test" is not positioned.

If you add position: relative to your container div, it will pick up that as the offsetParent and work properly. I don't know if this the fix you are looking for, but it works.

The alternative, of course, is using .parentElement instead of offsetParent, depending on your use-case.

use document.getElementById("item1").parentElement.scrollTop = 1000

offset parent is not meant to find the parent element of a node rather the "nearest table cell or root element" which in your case is the <body> tag. See the MDN Doc for offsetParent

发布评论

评论列表(0)

  1. 暂无评论