0

There is an old StackOverflow question on how to unhide/hide text using +/- symbols.

Cheeso posted a nice solution with some sample code. It was just what I was looking for, although the original poster didn't agree. :-)

I'm using the code on a web site that is intended to be used on mobile devices. The only problem is that the page jumps back to the top of the screen whenever the +/- is tapped.

Is there anyway to get around that? Thanks.

4

3 回答 3

2

In your click event handler, return false.

$('a.selector').click(function() {
    return false;
});
于 2012-06-04T21:45:13.137 回答
2

Here is the answer that Cheeso provided to me in email. I am posting it here for the benefit of others who follow. This didn't quite work and I am in the process of figuring out why.


If you change this line $('div p a[href="#"]').click(function() { expando(this); });

to this:

$('div p a[href="#"]').click(function(ev) { ev.preventDefault(); expando(this); });

...I think it should stop scrolling to the top.


When a user clicks on a link that has a hash character, the browser is expected to scroll to the location on the page where the fragment marker is placed. Like a bookmark. For example, in this URL: http://en.wikipedia.org/wiki/Causes_of_WWII#Militarism The fragment (bookmark) is #Militarism , and if you click that link, your browser will scroll to that section.

In the case of that sample I wrote, the hrefs are bare # characters, which implies an empty fragment. And I suppose the browser is scrolling to the default location, which (I guess) is "the top of the page".

To avoid this, just call ev.preventDefault() in the click handler. This is a jQuery trick that suppresses the normal handling of the click; in your case, it suppresses the part where the browser tries to scroll to a non-existent anchor.

于 2012-06-04T21:45:15.740 回答
1

Implement event.preventDefault() in the click handler.

$('a').click(function(e) {
    e.preventDefault();
    // more code here
});
于 2012-06-04T21:45:50.217 回答