To solve the offset problem, use two attributes: padding-top and maring-top.
Padding-top is used to solve the offset between the anchor area and the top.
Margin-top is used to solve the unnecessary offset generated by setting padding-top between the anchor area and the anchor area.
Padding-top uses a positive value, while maring-top uses a negative value. The two values are the same.
Example
The code is as follows: |
Copy code |
<! Doctype html> <Html lang = "en"> <Head> <Meta charset = "UTF-8"> <Title> \ front-end blog </title> <Style> Body { Padding-top: 100px; } *{ Margin: 0; Padding: 0; } # P1 { Background: yellow; Height: 300px; } # P2 {height: 800px; background: blue ;} # P3 {height: 800px; background: green ;} # P4 {height: 800px; background: red ;} # P4 {height: 800px; background: # ccc ;} # P5 {height: 800px; background: # aaa ;} Div [id * = p] { Font-size: 100px; } # Btn { Position: fixed; Left: 0; top: 0; Height: 100px; Line-height: 100px; Background: # f15f43; Width: 100%; Text-align: center; Padding: 10px 0; } # Btn { Background: #323841; Height: 100px; Padding: 0 40px; Font-size: 14px; Color: # fff; Display: inline-block; } </Style> </Head> <Body> <Div id = "btn"> <A id = "a1" href = "# p1"> # p1 </a> <A id = "a1" href = "# p2"> # p2 </a> <A id = "a1" href = "# p3"> # p3 </a> <A id = "a1" href = "# p4"> # p4 </a> <A id = "a1" href = "# p5"> # p5 </a> </Div> <Div id = "p1"> P1 </Div> <Div id = "p2"> P2 </Div> <Div id = "p3"> P3 </Div> <Div id = "p4"> P4 </Div> <Div id = "p5"> P5 </Div> </Body> </Html> <Script> Window. onload = function (){ Var oBtn = document. querySelector ("# btn "); Var aA = oBtn. querySelectorAll (""); For (var I = 0; I <aA. length; I ++ ){ AA [I]. onclick = function (ev ){ Var ev = ev | window. event; Var id = this. hash; Var thisId = document. querySelector (id ); Document.doc umentElement. scrollTop = document. body. scrollTop = thisId. OffsetTop-oBtn.offsetHeight; Ev. preventDefault (); } } } </Script> |