开发者

Safari - Javascript - Hiding/Showing Div causes scrollbar to be reset

I have a HTML document containing a series of Questions and Answers.

Each Question is contained in a div. Each Answer is contained in a div. Each Answer is given a unique id.

The CSS st开发者_JS百科yle for each Answer is set to 'none' in order to initially hide the element.

When a Question is clicked on, the div passes the id of the corresponding Answer to this function:

function toggle(id) {
    var state = document.getElementById(id).style.display;
    if (state == 'block') {
        document.getElementById(id).style.display = 'none';
    } else {
        document.getElementById(id).style.display = 'block';
    }
}

(This toggles the appearance of the Answer div.)

The problem: This mechanism works well in Safari if the scrollbar is at the default (top) position. Otherwise, this will cause the scrollbar to reset to the default position, effectively ruining the usefulness of this mechanism on long pages.

Q. Is there any way to prevent the scrollbar position from being reset?

Thanks.


You've said that you're using

<a href='#'>...</a>

...for the question. That's the problem, that's a link telling the browser to go to the top of the page. You have a couple of options for correcting it:

  1. Hook the click event on the link (or its parent, etc.) and cancel the default action. How you do that depends on how you hook the event. It sounds like you're already hooking the event, so this is probably the simplest solution. If you're using an onclick= style hook, return false; out of your handler function. If you're using addEventListener, use preventDefault on the event passed into it. (You will presumably already be aware that most versions of IE don't support addEventListener, but rather attachEvent; how you prevent the default is also different. This sort of thing is why I use a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over browser differences.)

  2. Use the javascript: pseudo-protocol instead of #, e.g.:

    <a href='javascript:;'>...</a>
    

    The pseudo-protocol tells the browser to run the script code in the href element. In the above, the code is just a ; (statement terminator), which does nothing. You could, of course, have it trigger your toggle function:

    <a href='javascript:toggle("foo");'>...</a>
    
  3. Don't use an a at all. Whether it's appropriate to use one depends on whether it really is conceptually a link, which is totally your call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜