简体   繁体   中英

HTML Navigation anchor should not jump to the Top of the Page

I try to create a website and have a problem with the "anchor" navigation. At the top of the page there is a fixed Header. When you scroll the main part disapears under the Header.

Now i have on the left side a navigation, to jump to different titles. But with the "anchor" function, the title always jumps to far. he already disapears under the header. Is there a posibility to jump just close to the top?

here is a fiddle example.

<div class="header">Header <br> <br> <a href="#Title2">Title2</a></div>
<div class="main">
    <h1>Title 1</h1>
    <h1 id="Title2">Title 2</h1> 
</div>

.header{
width:500px;
height:100px;
background-color: red;
position:fixed;

}
.main {
padding-top: 100px;
width:500px;
height:1000px;
background-color:lightblue;

}

http://jsfiddle.net/BLrUG/

click the "Title2" link, to see the problem.

thx BBallBoy

position fixed acts like absolute ... other elements dont know for the excisting of this header and they go over/under it.ur code is running right u need to add this :

*{margin:0;padding:0}

to clear the spaceses and ur page will look fine

maybe u are searching for this Jquery funcs :

You can use a JavaScript call to scroll to the element but fix the offset a bit so it isn't covered by the header.

function scrollTo(id) {
    var offset = 0;

    //Get element
    var obj = document.getElementById(id);

    //Determine offset  
    if (obj.offsetParent) {
        do {
            offset += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }

    //Account for header
    offset -= 120;

    window.scroll(0, offset);
}

Then instead of using the ID in the anchor you pass it to the function

<a href="javascript:void(0);" onclick="javascript:scrollTo('Title2');">Title2</a>

You'll need to play around with the offset fix to find the best value. You may also want to make it a parameter to the function to make it more reusable.

use top position in header class

 top:0px; 

and use div for both title paragraphs and set top margin for both para div .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM