display:none to display:block - How do I get the page to scroll down?
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:开发者_StackOverflow I have tried
var objDiv = document.getElementById("the_div_id");
objDiv.scrollTop = objDiv.scrollHeight;
The page just won't scroll down. Any ideas?
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.)
精彩评论