1

I'm an absolute newbie so please bear with me. I've read a lot of posts here that I think may be related to my question but I'm having a hard time understanding the solutions provided.

I'm trying to create an on-click horizontal accordion with just CSS. With Firefox it works just fine. The problem occurs in Chrome and Safari.

The problem is that every time the links are clicked the page scrolls down almost to the bottom of the page that you need to scroll back up in order to see the entire content. The links look like this:

 <h2><a href="#accordion1">title1</a></h2>

Needless to say this can be very annoying to the user. I've read somewhere that this can be avoided using JavaScript preventDefault(). How do I go about that? What are the other ways to prevent this?

4

1 回答 1

0

Edit - so it seems preventDefault() cancels all of the default behaviours(makes sense actually) - The first solution I presented turns out to be not a solution at all.

So, this actually proves quite hard to do.

After some searching I've come to the conclusion that it's not possible to cancel the scroll without also canceling the links default behaviour (hence the default in .preventDefault()).

What you can do is scroll back to where you were after the links scrolling is done, but even if you do it as soon as you possibly can, you'll still be able to see the scrolls hapenning on the browser - so it's an ugly solution. (you can see it here anyway - http://jsfiddle.net/joplomacedo/RpDyc/ ).

So, alternatives? Since as your doing it (I assume here you're using the :target pseudo class) you still need javascript, then forget the :target stuff and rely on javascript alone. It's simpler, cleaner and less 'hacky'.

Here's how I'd do it (jquery) -> http://jsfiddle.net/joplomacedo/AfzJY/

If you however insist on doing it with CSS then I'd recommend doing it as Chris Coyier suggests here by taking advantage not of :target but :checked. I won't further develop here since his article does that pretty well.

Before Edit

Are you using jquery? If so all you'd need is this:

$('a[href="#accordion1"]').on('click', function (e) {
   e.preventDefault();
});

If you're not using jquery then here's how to do it with pure javascript:

var cancels_links = document.getElementsByClassName('cancels-link');

var cancel = function cancel(e) {
    e.preventDefault();
};

for (var i = 0, max = cancels_links.length; i < max; i++) {
    cancels_links[i].addEventListener('click', cancel, false );
}

...this one requires you to add class="cancels-link" to each 'a' element who's default behaviour you want to cancel.

Here's a fiddle with the two solutions -> http://jsfiddle.net/cBQnv/3/

于 2012-06-30T23:18:52.073 回答