Prevent browser from vertical scrolling after clic

2019-08-30 08:25发布

问题:

In the middle of my page I got a tiny menu, when you click a button it will horizontally scroll to the content you've chosen. But when you click it the entire window scrolls so the menu is on the top. Here's the graphical representation of my issue.

http://imgur.com/yJe7wg8

Here's the code I'm going to modify and use:

<div id="left">
<a href="#target1" class="panel">Target 1</a><br/>
<a href="#target2" class="panel">Target 2</a><br/>
<a href="#target3" class="panel">Target 3</a><br/>

<div id="right">
<div class="panel" id="target1" style="background:green">Target 1</div>
<div class="panel" id="target2" style="background:red">Target 2</div>
<div class="panel" id="target3" style="background:yellow">Target 3</div>

+some jQuery to make it slide from #left to #right

Here's the working demo:

http://jsfiddle.net/codeSpy/KyV6L/

回答1:

The default action of a # link is to navigate the the named ID. You need to prevent the default action:

$('a.panel').click(function(e) {
    e.preventDefault();

    /* rest of your function ... */
});


回答2:

Use a return false or a preventDefault() in your click event:

$('a.panel').click(function(e) {
    e.preventDefault();
    // ...
};


回答3:

You need to prevent the default action of the click event using preventDefault():

$('a.panel').click(function(e) {
    e.preventDefault();
    ...
});


回答4:

I think the problem you're having might be coming from the hrefs you're using. As they're actual urls, they try to navigate (scroll) to the anchors that you define with the #'s. Cause they don't exist, the page will automaticly scroll to the top of your site.

Try using ID's as attributes instead, or as the other answers suggested prevent the default action.