admin管理员组

文章数量:1327928

I am using javascript to change the display of a div tag with an onclick event. The div is at the bottom of the page, when and/or if needed the user can open the div. How can I get the page to scroll down when this div is changed to display:block?

FYI: I have tried

var objDiv = document.getElementById("the_div_id");
objDiv.scrollTop = objDiv.scrollHeight;

The page just won't scroll down. Any ideas?

I am using javascript to change the display of a div tag with an onclick event. The div is at the bottom of the page, when and/or if needed the user can open the div. How can I get the page to scroll down when this div is changed to display:block?

FYI: I have tried

var objDiv = document.getElementById("the_div_id");
objDiv.scrollTop = objDiv.scrollHeight;

The page just won't scroll down. Any ideas?

Share Improve this question edited Sep 12, 2010 at 6:11 Daniel Vandersluis 94.3k23 gold badges173 silver badges158 bronze badges asked Sep 12, 2010 at 6:07 MP123MP123 2751 gold badge6 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7
var objDiv = document.getElementById("the_div_id");
objDiv.scrollIntoView();

Something like this would work

Add an anchor by the div

<a href="#div" id="showDivTrigger">
<a name="div"></a>
<div style="display:none;">
contents
</div>
<script>
var element = document.getElementById('#div');
element.style.display = '';
</script>

scrollTop only makes sense on elements which themselves have a scrollbar (or do not, but can be scrolled). From the MSDN documentation: This property is always 0 for objects that do not have scroll bars. For these objects, setting the property has no effect.

You chould set body.scrollTop instead (or use window.scrollTo which has the same effect), for which you need the absolute position of the element in the page, which you can get by walking up the element's offsetParent chain and summing up offsetTop distances. You are probably better off using a framework, e.g. jQuery's offset method, than doing this manually. (Of course, if you only need to jump to the element and not visually scroll, then mplungjan's solution is the simplest.)

本文标签: javascriptdisplaynone to displayblockHow do I get the page to scroll downStack Overflow