固定页眉与页内锚重叠

时间:2022-03-08 20:00:33

If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:

如果在HTML页面中有一个不滚动的标题,固定在顶部,有一个定义的高度:

Is there a way to use the URL anchor (the #fragment part) to have the browser scroll to a certain point in the page, but still respect the height of the fixed element without the help of JavaScript?

是否有一种方法可以使用URL锚点(#fragment part)让浏览器滚动到页面的某个点,但在没有JavaScript帮助的情况下仍然尊重固定元素的高度?

http://foo.com/#bar
WRONG (but the common behavior):         CORRECT:
+---------------------------------+      +---------------------------------+
| BAR///////////////////// header |      | //////////////////////// header |
+---------------------------------+      +---------------------------------+
| Here is the rest of the Text    |      | BAR                             |
| ...                             |      |                                 |
| ...                             |      | Here is the rest of the Text    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+

25 个解决方案

#1


105  

I had the same problem. I solved it by adding a class to the anchor element with the topbar height as the padding-top value.

我也有同样的问题。我通过向锚元素添加一个类来解决这个问题,锚元素的顶栏高度作为桨叶顶值。

<h1><a class="anchor" name="barlink">Bar</a></h1>

And then simply the css:

然后就是css:

.anchor { padding-top: 90px; }

#2


134  

If you can't or don't want to set a new class, in css:

如果你不能或不想在css中设置一个新类:

:target:before {
  content:"";
  display:block;
  height:60px; /* fixed header height*/
  margin:-60px 0 0; /* negative fixed header height */
}

or jQuery:

或jQuery:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

#3


109  

I use this approach:

我用这个方法:

/* add class="jumptarget" to all targets. */

.jumptarget::before {
  content:"";
  display:block;
  height:50px; /* fixed header height*/
  margin:-50px 0 0; /* negative fixed header height */
}

It adds an invisible element before each target. It works IE8+.

它在每个目标之前添加一个不可见的元素。它是IE8 +。

Here are more solutions: http://nicolasgallagher.com/jump-links-and-viewport-positioning/

这里有更多的解决方案:http://nicolasgallagher.com/jump-link -viewport-positioning/

#4


26  

Official Bootstrap Adopted Answer:

官方引导采用回答:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; // Set the Appropriate Height
  height: 75px; // Set the Appropriate Height
  visibility: hidden; 
}

Credits

学分

Merge

合并

#5


21  

The best way that I found to handle this issue is (replace 65px with your fixed element height):

我发现处理这个问题的最好方法是(用固定的元素高度替换65px):

div:target {
  padding-top: 65px; 
  margin-top: -65px;
}

If you do not like to use the target selector you can also do it in this way:

如果你不喜欢使用目标选择器,你也可以这样做:

.my-target {
    padding-top: 65px;
    margin-top: -65px;
}

Note: this example will not work if the target element have a backgound color that differant from his parent. for example:

注意:如果目标元素具有与父元素不同的背景色,则此示例将不起作用。例如:

<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>

in this case the green color of my-target element will overwrite his parent red element in 65px. I did not find any pure CSS solution to handle this issue but if you do not have another background color this solution is the best.

在这种情况下,my-target元素的绿色将覆盖其父元素在65px中的红色。我没有找到任何纯粹的CSS解决方案来处理这个问题,但是如果您没有其他背景颜色,这个解决方案是最好的。

#6


10  

While some of the proposed solutions work for fragment links (= hash links) within the same page (like a menu link that scrolls down), I found that none of them worked in current Chrome when you want to use fragment links coming in from other pages.

虽然一些提议的解决方案适用于同一页面中的片段链接(=哈希链接)(比如滚动的菜单链接),但我发现,当您希望使用来自其他页面的片段链接时,它们在当前的Chrome中都不起作用。

So calling www.mydomain.com/page.html#foo from scratch will NOT offset your target in current Chrome with any of the given CSS solutions or JS solutions.

因此,从头调用www.dommyain.com/page.html #foo不会用任何给定的CSS解决方案或JS解决方案来抵消当前Chrome中的目标。

There is also a jQuery bug report describing some details of the problem.

还有一个jQuery错误报告描述了问题的一些细节。

SOLUTION

解决方案

The only option I found so far that really works in Chrome is JavaScript that is not called onDomReady but with a delay.

到目前为止,我发现在Chrome中唯一可行的选项是JavaScript,它不是onDomReady,而是延迟。

// set timeout onDomReady
$(function() {
    setTimeout(delayedFragmentTargetOffset, 500);
});

// add scroll offset to fragment target (if there is one)
function delayedFragmentTargetOffset(){
    var offset = $(':target').offset();
    if(offset){
        var scrollto = offset.top - 95; // minus fixed header height
        $('html, body').animate({scrollTop:scrollto}, 0);
    }
}

SUMMARY

总结

Without a JS delay solutions will probably work in Firefox, IE, Safari, but not in Chrome.

没有JS延迟解决方案可能在Firefox、IE、Safari中有效,但在Chrome中不行。

#7


8  

For Chrome/Safari/Firefox you could add a display: block and use a negative margin to compensate the offset, like:

对于Chrome/Safari/Firefox,你可以添加一个显示:块并使用一个负的空白来补偿偏移量,比如:

a[name] {
    display: block;
    padding-top: 90px;
    margin-top: -90px;
}

See example http://codepen.io/swed/pen/RrZBJo

看到http://codepen.io/swed/pen/RrZBJo的例子

#8


6  

You can do this with jQuery:

可以使用jQuery:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);

#9


5  

It works for me:

它适合我:

HTML LINK to Anchor:

HTML链接锚:

<a href="#security">SECURITY</a>

HTML Anchor:

HTML锚:

<a name="security" class="anchor"></a>

CSS :

CSS:

.anchor::before {
    content: "";
    display: block;
    margin-top: -50px;
    position: absolute;
}

#10


4  

You could try this:

你可以试试这个:

<style>
h1:target { padding-top: 50px; }
</style>

<a href="#bar">Go to bar</a>

<h1 id="bar">Bar</h1>

Set the top padding value to the actual height of your header. This will introduce a slight extra gap at the top of your header, but it will only be visible when the user jumps to the anchor and then scrolls up. I've made up that solution for my site right now, but it only shows a small fixed bar at the top of the page, nothing too high.

将顶边值设置为标题的实际高度。这将在标题顶部引入一个额外的间隙,但是只有当用户跳转到锚点并向上滚动时才能看到它。我已经为我的站点设计了这个解决方案,但是它只显示了页面顶部的一个小的固定条,没有太高的地方。

#11


4  

I've got it working easily with CSS and HTML, using the "anchor:before" method mentioned above. I think it works the best, because it doesn't create massive padding between your divs.

我已经用CSS和HTML轻松地工作了,使用了上面提到的“锚:before”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。

.anchor:before {
  content:"";
  display:block;
  height:60px; /* fixed header height*/
  margin:-60px 0 0; /* negative fixed header height */
}

It doesn't seem to work for the first div on the page, but you can counter that by adding padding to that first div.

它似乎并不适用于页面上的第一个div,但是您可以通过向第一个div添加填充来解决这个问题。

#anchor-one{padding-top: 60px;}

Here's a working fiddle: http://jsfiddle.net/FRpHE/24/

这里有一个工作的小提琴:http://jsfiddle.net/FRpHE/24/。

#12


3  

It feels somewhat hacky to my purist mind but as a css-only solution you can add padding to the active anchored element using the :target selector:

这对我的纯粹主义者来说有点陈腐,但是作为一个只有css的解决方案,您可以使用:target selector向活动锚定元素添加填充:

html, body {height:100%; min-height:100%; margin:0;}
body {min-height:200%;}
header {display:inline-block; position:fixed; font-size:1.5em; height:100px; top:0; left:0; right:0; line-height:100px; background:black; text-align:center;}
header a {color:#fff;}
section {padding:30px; margin:20px;}
section:first-of-type, section:target {padding-top:130px;}
<header><a href="#one">#One</a> <a href="#two">#two</a> <a href="#three">#three</a></header>
<section id="one"><h1>One</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>
<section id="two"><h1>Two</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>
<section id="three"><h1>Three</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>

#13


2  

I found I had to use both MutttenXd's and Badabam's CSS solutions together, as the first did not work in Chrome and the second did not work in Firefox:

我发现我必须同时使用MutttenXd和Badabam的CSS解决方案,因为第一个在Chrome中不能用,第二个在Firefox中不能用:

a.anchor { 
  padding-top: 90px;
}

a.anchor:before { 
  display: block;
  content: "";
  height: 90px;
  margin-top: -90px;
}

<a class="anchor" name="shipping"></a><h2>Shipping (United States)</h2>
...

#14


2  

I'm using @Jpsy's answer, but for performance reasons I'm only setting the timer if the hash is present in the URL.

我使用@Jpsy的答案,但出于性能原因,我只在URL中显示散列时设置计时器。

$(function() {
      // Only set the timer if you have a hash
      if(window.location.hash) {
        setTimeout(delayedFragmentTargetOffset, 500);
      }
  });

function delayedFragmentTargetOffset(){
      var offset = $(':target').offset();
      if(offset){
          var scrollto = offset.top - 80; // minus fixed header height
          $('html, body').animate({scrollTop:scrollto}, 0);
          $(':target').highlight();
      }
  };

#15


2  

The way that I find being the cleanest is the following one :

我发现最干净的方法是:

  #bar::before {
    display: block;
    content: " ";
    margin-top: -150px;
    height: 150px;
    visibility: hidden;
    pointer-events: none;
  }

#16


1  

<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

This code should do the trick. Swap out 45px for the height of your header bar.

这段代码应该很有用。用45px换掉标题栏的高度。

EDIT: If using jQuery is an option, I've also been successful using jQuery.localScroll with an offset value set. The offset option is a part of jQuery.scrollTo, which jQuery.localScroll is built upon. A demo is available here: http://demos.flesler.com/jquery/scrollTo/ (second window, under 'offset')

编辑:如果使用jQuery是一种选择,那么我使用jQuery也很成功。带有偏移值集的localScroll。偏移选项是jQuery的一部分。scrollTo,jQuery。localScroll是建立在。这里有一个演示:http://demos.flesler.com/jquery/scrollTo/(第二个窗口,在'offset'下)

#17


1  

Here is a complete jquery solution that will work in IE:

这是一个完整的jquery解决方案,可以在IE中使用:

Suppose the navigation bar elements are something like this:

假设导航条元素是这样的:

<ul>
    <li><a class="navigation" href="/#contact-us">Contact us</a></li>
    <li><a class="navigation" href="/#about-us">About us</a></li>
</ul>

You can use the following jquery snippet to offset the scroll:

您可以使用以下jquery代码片段来抵消滚动条:

$(function() {
    $("a.navigation").click(function(event) {
        event.preventDefault();
        offSetScroll($(this));
    });
    offSetScrollFromLocation(window.location.href.toLowerCase());
});

function offSetScroll(anchor) {
    var href = anchor.attr("href");
    offSetScrollFromLocation(href);
}

function offSetScrollFromLocation(href) {
    //Change this according to the height of the navigation bar
    var fromTop = 250;
    if(href.indexOf("#")<=0)
        return;
    var hash=href.substring(href.indexOf("#"));
    var targetOffset = $(hash).offset().top-fromTop;
    $('html, body').animate({scrollTop: targetOffset}, 400, function(e) {

    });
}

#18


1  

Implemented using :before worked great until we realized that the pseudo element was actually covering and blocking pointer events that sat within the pseudo element's area. Using something like pointer-events: none on the :before or even directly on the anchor had no affect.

使用:before非常有用,直到我们意识到pseudo元素实际上覆盖和阻塞位于pseudo元素区域内的指针事件。使用诸如指针事件:在:之前或甚至直接在锚点上没有任何影响。

What we ended up doing was making the anchor's positioning absolute and then adjusting it's position to be the offset/height of the fixed area.

我们最后做的是使锚定位绝对然后调整它的位置偏移量/固定区域的高度。

Offset Anchor without Blocking Pointer Events

没有阻塞指针事件的偏移锚

.section-marker {

    position: absolute;
    top: -300px;
}

The value with this is that we're not blocking any elements that might fall within those 300px. The downside is that grabbing that element's position from Javascript needs to take into account that offset so any logic there had to be adjusted.

这里的值是,我们没有屏蔽任何可能在300px内的元素。缺点是,从Javascript获取元素的位置需要考虑到偏移量,因此必须调整其中的任何逻辑。

#19


1  

This is how I got it to finally go to the proper place when you click on the navigation. I added an event handler for the navigation clicks. Then you can just use "scrollBy" to move up on the offset.

这就是当你点击导航时,我最终到达正确位置的方法。我为导航单击添加了一个事件处理程序。然后您可以使用“scrollBy”在偏移量上向上移动。

var offset = 90;

 $('.navbar li a').click(function(event) {
    event.preventDefault();
    $($(this).attr('href'))[0].scrollIntoView();
    scrollBy(0, -offset);
 });

#20


1  

A minimally intrusive approach using jQuery:

使用jQuery的一种最小化入侵方法:

Link:

链接:

<a href="#my-anchor-1" class="anchor-link">Go To Anchor 1</a>

Content:

内容:

<h3 id="my-anchor-1">Here is Anchor 1</a>

Script:

脚本:

$(".anchor-link").click(function() {
    var headerHeight = 120;
    $('html, body').stop(true, true).animate({
        scrollTop: $(this.hash).offset().top - headerHeight
    }, 750);
    return false;
});

By assigning the anchor-link class to the links, the behaviour of other links (like accordion or tab controls) are not affected.

通过将锚定链接类分配给链接,其他链接(如手风琴导航或选项卡控件)的行为不会受到影响。

The question doesn't want javascript but the other more popular question is closed because of this one and I couldn't answer there.

这个问题不需要javascript,但另一个更流行的问题因为这个问题被关闭了,我无法回答。

#21


0  

// handle hashes when page loads
// <http://*.com/a/29853395>
function adjustAnchor() {
  const $anchor = $(':target');
  const fixedElementHeight = $('.navbar-fixed-top').outerHeight();
  if ($anchor.length > 0)
    window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
}
$(window).on('hashchange load', adjustAnchor);
$('body').on('click', "a[href^='#']", function (ev) {
  if (window.location.hash === $(this).attr('href')) {
    ev.preventDefault();
    adjustAnchor();
  }
});

#22


0  

I use this method because for some reason, none of the other solutions proposed actually worked for me. I promise I tried.

我使用这个方法是因为,由于某种原因,其他的解决方案都没有对我有效。我保证我试过了。

section {
   position: relative;
   border-top: 52px solid transparent; /* navbar height +2 */
   margin: -30px 0 0;
   -webkit-background-clip: padding-box;
   -moz-background-clip: padding;
   background-clip: padding-box;
}

section:before {
   content: "";
   position: absolute;
   top: -2px;
   left: 0;
   right: 0;
   border-top: 2px solid transparent;
}

Replace section by a class if you prefer.

如果您愿意,可以用类替换section。

source: Jump links and viewport positioning

源:跳转链接和viewport定位

  • Tested on Firefox 45 and Chrome 52.
  • 在Firefox 45和Chrome 52上测试过。
  • bootstrap version: 3.3.7
  • 引导程序版本:3.3.7

For those who do not believe me I kindly prepared a jsfiddle with the solution in it: SOLUTION

对于那些不相信我的人,我善意地准备了一个jsfiddle中的解决方案:solution

#23


0  

Add a class with a "paddingtop", so it works ;)

添加一个具有“paddingtop”的类,这样才有效;

<h1><a class="paddingtop">Bar</a></h1>

And for css you have:

对于css,你有:

    .paddingtop{ 
       padding-top: 90px; 
     }

#24


0  

A very simple CSS only answer is to put this at the top of your stylesheet:

一个非常简单的CSS解决方案是将它放在样式表的顶部:

a{padding-top: 90px;}
a:link{padding-top: unset;}

The first style regulates all anchor tags where the second styles anchor tags with a hyperlink.

第一个样式管理所有锚标记,第二个样式使用超链接锚标记。

Note: This currently works in Firefox and Edge but nor in Chrome.

注意:这在Firefox和Edge中有效,但在Chrome中无效。

#25


-1  

CSS trick will be a workaround. A proper solution which will work in all scenario can be implemented using jQuery.

CSS技巧将是一个解决方案。一个适用于所有场景的合适解决方案可以使用jQuery实现。

Refer to https://codepen.io/pikeshmn/pen/mMxEdZ

指的是https://codepen.io/pikeshmn/pen/mMxEdZ

Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight And offset the scroll to this value.

方法:使用document.getElementById('header')获取固定资产净值的高度。从右侧偏移滚动到这个值。

var jump=function(e){  

e.preventDefault();                        //prevent "hard" jump
  var target = $(this).attr("href");       //get the target

      //perform animated scrolling
      $('html,body').animate(
        {
          scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5  //get top-position of target-element and set it as scroll target
        },1000,function()                  //scrolldelay: 1 seconds
        {
          location.hash = target;          //attach the hash (#jumptarget) to the pageurl
        });
      }

  $(document).ready(function()
  {
    $('a[href*="#"]').bind("click", jump); //get all hrefs
    return false;
  });

P.S:

注:

  • It includes a nice 5 pixels difference between header and target
  • 它包括一个漂亮的5像素的不同的头部和目标。
  • Scroll effect is not hard, rather smooth; Smooth Scrolling
  • 滚动效果不硬,相当平滑;平滑滚动

#1


105  

I had the same problem. I solved it by adding a class to the anchor element with the topbar height as the padding-top value.

我也有同样的问题。我通过向锚元素添加一个类来解决这个问题,锚元素的顶栏高度作为桨叶顶值。

<h1><a class="anchor" name="barlink">Bar</a></h1>

And then simply the css:

然后就是css:

.anchor { padding-top: 90px; }

#2


134  

If you can't or don't want to set a new class, in css:

如果你不能或不想在css中设置一个新类:

:target:before {
  content:"";
  display:block;
  height:60px; /* fixed header height*/
  margin:-60px 0 0; /* negative fixed header height */
}

or jQuery:

或jQuery:

var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);

#3


109  

I use this approach:

我用这个方法:

/* add class="jumptarget" to all targets. */

.jumptarget::before {
  content:"";
  display:block;
  height:50px; /* fixed header height*/
  margin:-50px 0 0; /* negative fixed header height */
}

It adds an invisible element before each target. It works IE8+.

它在每个目标之前添加一个不可见的元素。它是IE8 +。

Here are more solutions: http://nicolasgallagher.com/jump-links-and-viewport-positioning/

这里有更多的解决方案:http://nicolasgallagher.com/jump-link -viewport-positioning/

#4


26  

Official Bootstrap Adopted Answer:

官方引导采用回答:

*[id]:before { 
  display: block; 
  content: " "; 
  margin-top: -75px; // Set the Appropriate Height
  height: 75px; // Set the Appropriate Height
  visibility: hidden; 
}

Credits

学分

Merge

合并

#5


21  

The best way that I found to handle this issue is (replace 65px with your fixed element height):

我发现处理这个问题的最好方法是(用固定的元素高度替换65px):

div:target {
  padding-top: 65px; 
  margin-top: -65px;
}

If you do not like to use the target selector you can also do it in this way:

如果你不喜欢使用目标选择器,你也可以这样做:

.my-target {
    padding-top: 65px;
    margin-top: -65px;
}

Note: this example will not work if the target element have a backgound color that differant from his parent. for example:

注意:如果目标元素具有与父元素不同的背景色,则此示例将不起作用。例如:

<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>

in this case the green color of my-target element will overwrite his parent red element in 65px. I did not find any pure CSS solution to handle this issue but if you do not have another background color this solution is the best.

在这种情况下,my-target元素的绿色将覆盖其父元素在65px中的红色。我没有找到任何纯粹的CSS解决方案来处理这个问题,但是如果您没有其他背景颜色,这个解决方案是最好的。

#6


10  

While some of the proposed solutions work for fragment links (= hash links) within the same page (like a menu link that scrolls down), I found that none of them worked in current Chrome when you want to use fragment links coming in from other pages.

虽然一些提议的解决方案适用于同一页面中的片段链接(=哈希链接)(比如滚动的菜单链接),但我发现,当您希望使用来自其他页面的片段链接时,它们在当前的Chrome中都不起作用。

So calling www.mydomain.com/page.html#foo from scratch will NOT offset your target in current Chrome with any of the given CSS solutions or JS solutions.

因此,从头调用www.dommyain.com/page.html #foo不会用任何给定的CSS解决方案或JS解决方案来抵消当前Chrome中的目标。

There is also a jQuery bug report describing some details of the problem.

还有一个jQuery错误报告描述了问题的一些细节。

SOLUTION

解决方案

The only option I found so far that really works in Chrome is JavaScript that is not called onDomReady but with a delay.

到目前为止,我发现在Chrome中唯一可行的选项是JavaScript,它不是onDomReady,而是延迟。

// set timeout onDomReady
$(function() {
    setTimeout(delayedFragmentTargetOffset, 500);
});

// add scroll offset to fragment target (if there is one)
function delayedFragmentTargetOffset(){
    var offset = $(':target').offset();
    if(offset){
        var scrollto = offset.top - 95; // minus fixed header height
        $('html, body').animate({scrollTop:scrollto}, 0);
    }
}

SUMMARY

总结

Without a JS delay solutions will probably work in Firefox, IE, Safari, but not in Chrome.

没有JS延迟解决方案可能在Firefox、IE、Safari中有效,但在Chrome中不行。

#7


8  

For Chrome/Safari/Firefox you could add a display: block and use a negative margin to compensate the offset, like:

对于Chrome/Safari/Firefox,你可以添加一个显示:块并使用一个负的空白来补偿偏移量,比如:

a[name] {
    display: block;
    padding-top: 90px;
    margin-top: -90px;
}

See example http://codepen.io/swed/pen/RrZBJo

看到http://codepen.io/swed/pen/RrZBJo的例子

#8


6  

You can do this with jQuery:

可以使用jQuery:

var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);

#9


5  

It works for me:

它适合我:

HTML LINK to Anchor:

HTML链接锚:

<a href="#security">SECURITY</a>

HTML Anchor:

HTML锚:

<a name="security" class="anchor"></a>

CSS :

CSS:

.anchor::before {
    content: "";
    display: block;
    margin-top: -50px;
    position: absolute;
}

#10


4  

You could try this:

你可以试试这个:

<style>
h1:target { padding-top: 50px; }
</style>

<a href="#bar">Go to bar</a>

<h1 id="bar">Bar</h1>

Set the top padding value to the actual height of your header. This will introduce a slight extra gap at the top of your header, but it will only be visible when the user jumps to the anchor and then scrolls up. I've made up that solution for my site right now, but it only shows a small fixed bar at the top of the page, nothing too high.

将顶边值设置为标题的实际高度。这将在标题顶部引入一个额外的间隙,但是只有当用户跳转到锚点并向上滚动时才能看到它。我已经为我的站点设计了这个解决方案,但是它只显示了页面顶部的一个小的固定条,没有太高的地方。

#11


4  

I've got it working easily with CSS and HTML, using the "anchor:before" method mentioned above. I think it works the best, because it doesn't create massive padding between your divs.

我已经用CSS和HTML轻松地工作了,使用了上面提到的“锚:before”方法。我认为它是最好的,因为它不会在你的divs之间产生大量的填充。

.anchor:before {
  content:"";
  display:block;
  height:60px; /* fixed header height*/
  margin:-60px 0 0; /* negative fixed header height */
}

It doesn't seem to work for the first div on the page, but you can counter that by adding padding to that first div.

它似乎并不适用于页面上的第一个div,但是您可以通过向第一个div添加填充来解决这个问题。

#anchor-one{padding-top: 60px;}

Here's a working fiddle: http://jsfiddle.net/FRpHE/24/

这里有一个工作的小提琴:http://jsfiddle.net/FRpHE/24/。

#12


3  

It feels somewhat hacky to my purist mind but as a css-only solution you can add padding to the active anchored element using the :target selector:

这对我的纯粹主义者来说有点陈腐,但是作为一个只有css的解决方案,您可以使用:target selector向活动锚定元素添加填充:

html, body {height:100%; min-height:100%; margin:0;}
body {min-height:200%;}
header {display:inline-block; position:fixed; font-size:1.5em; height:100px; top:0; left:0; right:0; line-height:100px; background:black; text-align:center;}
header a {color:#fff;}
section {padding:30px; margin:20px;}
section:first-of-type, section:target {padding-top:130px;}
<header><a href="#one">#One</a> <a href="#two">#two</a> <a href="#three">#three</a></header>
<section id="one"><h1>One</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>
<section id="two"><h1>Two</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>
<section id="three"><h1>Three</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>

#13


2  

I found I had to use both MutttenXd's and Badabam's CSS solutions together, as the first did not work in Chrome and the second did not work in Firefox:

我发现我必须同时使用MutttenXd和Badabam的CSS解决方案,因为第一个在Chrome中不能用,第二个在Firefox中不能用:

a.anchor { 
  padding-top: 90px;
}

a.anchor:before { 
  display: block;
  content: "";
  height: 90px;
  margin-top: -90px;
}

<a class="anchor" name="shipping"></a><h2>Shipping (United States)</h2>
...

#14


2  

I'm using @Jpsy's answer, but for performance reasons I'm only setting the timer if the hash is present in the URL.

我使用@Jpsy的答案,但出于性能原因,我只在URL中显示散列时设置计时器。

$(function() {
      // Only set the timer if you have a hash
      if(window.location.hash) {
        setTimeout(delayedFragmentTargetOffset, 500);
      }
  });

function delayedFragmentTargetOffset(){
      var offset = $(':target').offset();
      if(offset){
          var scrollto = offset.top - 80; // minus fixed header height
          $('html, body').animate({scrollTop:scrollto}, 0);
          $(':target').highlight();
      }
  };

#15


2  

The way that I find being the cleanest is the following one :

我发现最干净的方法是:

  #bar::before {
    display: block;
    content: " ";
    margin-top: -150px;
    height: 150px;
    visibility: hidden;
    pointer-events: none;
  }

#16


1  

<div style="position:relative; top:-45px;">
    <a name="fragment"> </a>
</div>

This code should do the trick. Swap out 45px for the height of your header bar.

这段代码应该很有用。用45px换掉标题栏的高度。

EDIT: If using jQuery is an option, I've also been successful using jQuery.localScroll with an offset value set. The offset option is a part of jQuery.scrollTo, which jQuery.localScroll is built upon. A demo is available here: http://demos.flesler.com/jquery/scrollTo/ (second window, under 'offset')

编辑:如果使用jQuery是一种选择,那么我使用jQuery也很成功。带有偏移值集的localScroll。偏移选项是jQuery的一部分。scrollTo,jQuery。localScroll是建立在。这里有一个演示:http://demos.flesler.com/jquery/scrollTo/(第二个窗口,在'offset'下)

#17


1  

Here is a complete jquery solution that will work in IE:

这是一个完整的jquery解决方案,可以在IE中使用:

Suppose the navigation bar elements are something like this:

假设导航条元素是这样的:

<ul>
    <li><a class="navigation" href="/#contact-us">Contact us</a></li>
    <li><a class="navigation" href="/#about-us">About us</a></li>
</ul>

You can use the following jquery snippet to offset the scroll:

您可以使用以下jquery代码片段来抵消滚动条:

$(function() {
    $("a.navigation").click(function(event) {
        event.preventDefault();
        offSetScroll($(this));
    });
    offSetScrollFromLocation(window.location.href.toLowerCase());
});

function offSetScroll(anchor) {
    var href = anchor.attr("href");
    offSetScrollFromLocation(href);
}

function offSetScrollFromLocation(href) {
    //Change this according to the height of the navigation bar
    var fromTop = 250;
    if(href.indexOf("#")<=0)
        return;
    var hash=href.substring(href.indexOf("#"));
    var targetOffset = $(hash).offset().top-fromTop;
    $('html, body').animate({scrollTop: targetOffset}, 400, function(e) {

    });
}

#18


1  

Implemented using :before worked great until we realized that the pseudo element was actually covering and blocking pointer events that sat within the pseudo element's area. Using something like pointer-events: none on the :before or even directly on the anchor had no affect.

使用:before非常有用,直到我们意识到pseudo元素实际上覆盖和阻塞位于pseudo元素区域内的指针事件。使用诸如指针事件:在:之前或甚至直接在锚点上没有任何影响。

What we ended up doing was making the anchor's positioning absolute and then adjusting it's position to be the offset/height of the fixed area.

我们最后做的是使锚定位绝对然后调整它的位置偏移量/固定区域的高度。

Offset Anchor without Blocking Pointer Events

没有阻塞指针事件的偏移锚

.section-marker {

    position: absolute;
    top: -300px;
}

The value with this is that we're not blocking any elements that might fall within those 300px. The downside is that grabbing that element's position from Javascript needs to take into account that offset so any logic there had to be adjusted.

这里的值是,我们没有屏蔽任何可能在300px内的元素。缺点是,从Javascript获取元素的位置需要考虑到偏移量,因此必须调整其中的任何逻辑。

#19


1  

This is how I got it to finally go to the proper place when you click on the navigation. I added an event handler for the navigation clicks. Then you can just use "scrollBy" to move up on the offset.

这就是当你点击导航时,我最终到达正确位置的方法。我为导航单击添加了一个事件处理程序。然后您可以使用“scrollBy”在偏移量上向上移动。

var offset = 90;

 $('.navbar li a').click(function(event) {
    event.preventDefault();
    $($(this).attr('href'))[0].scrollIntoView();
    scrollBy(0, -offset);
 });

#20


1  

A minimally intrusive approach using jQuery:

使用jQuery的一种最小化入侵方法:

Link:

链接:

<a href="#my-anchor-1" class="anchor-link">Go To Anchor 1</a>

Content:

内容:

<h3 id="my-anchor-1">Here is Anchor 1</a>

Script:

脚本:

$(".anchor-link").click(function() {
    var headerHeight = 120;
    $('html, body').stop(true, true).animate({
        scrollTop: $(this.hash).offset().top - headerHeight
    }, 750);
    return false;
});

By assigning the anchor-link class to the links, the behaviour of other links (like accordion or tab controls) are not affected.

通过将锚定链接类分配给链接,其他链接(如手风琴导航或选项卡控件)的行为不会受到影响。

The question doesn't want javascript but the other more popular question is closed because of this one and I couldn't answer there.

这个问题不需要javascript,但另一个更流行的问题因为这个问题被关闭了,我无法回答。

#21


0  

// handle hashes when page loads
// <http://*.com/a/29853395>
function adjustAnchor() {
  const $anchor = $(':target');
  const fixedElementHeight = $('.navbar-fixed-top').outerHeight();
  if ($anchor.length > 0)
    window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
}
$(window).on('hashchange load', adjustAnchor);
$('body').on('click', "a[href^='#']", function (ev) {
  if (window.location.hash === $(this).attr('href')) {
    ev.preventDefault();
    adjustAnchor();
  }
});

#22


0  

I use this method because for some reason, none of the other solutions proposed actually worked for me. I promise I tried.

我使用这个方法是因为,由于某种原因,其他的解决方案都没有对我有效。我保证我试过了。

section {
   position: relative;
   border-top: 52px solid transparent; /* navbar height +2 */
   margin: -30px 0 0;
   -webkit-background-clip: padding-box;
   -moz-background-clip: padding;
   background-clip: padding-box;
}

section:before {
   content: "";
   position: absolute;
   top: -2px;
   left: 0;
   right: 0;
   border-top: 2px solid transparent;
}

Replace section by a class if you prefer.

如果您愿意,可以用类替换section。

source: Jump links and viewport positioning

源:跳转链接和viewport定位

  • Tested on Firefox 45 and Chrome 52.
  • 在Firefox 45和Chrome 52上测试过。
  • bootstrap version: 3.3.7
  • 引导程序版本:3.3.7

For those who do not believe me I kindly prepared a jsfiddle with the solution in it: SOLUTION

对于那些不相信我的人,我善意地准备了一个jsfiddle中的解决方案:solution

#23


0  

Add a class with a "paddingtop", so it works ;)

添加一个具有“paddingtop”的类,这样才有效;

<h1><a class="paddingtop">Bar</a></h1>

And for css you have:

对于css,你有:

    .paddingtop{ 
       padding-top: 90px; 
     }

#24


0  

A very simple CSS only answer is to put this at the top of your stylesheet:

一个非常简单的CSS解决方案是将它放在样式表的顶部:

a{padding-top: 90px;}
a:link{padding-top: unset;}

The first style regulates all anchor tags where the second styles anchor tags with a hyperlink.

第一个样式管理所有锚标记,第二个样式使用超链接锚标记。

Note: This currently works in Firefox and Edge but nor in Chrome.

注意:这在Firefox和Edge中有效,但在Chrome中无效。

#25


-1  

CSS trick will be a workaround. A proper solution which will work in all scenario can be implemented using jQuery.

CSS技巧将是一个解决方案。一个适用于所有场景的合适解决方案可以使用jQuery实现。

Refer to https://codepen.io/pikeshmn/pen/mMxEdZ

指的是https://codepen.io/pikeshmn/pen/mMxEdZ

Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight And offset the scroll to this value.

方法:使用document.getElementById('header')获取固定资产净值的高度。从右侧偏移滚动到这个值。

var jump=function(e){  

e.preventDefault();                        //prevent "hard" jump
  var target = $(this).attr("href");       //get the target

      //perform animated scrolling
      $('html,body').animate(
        {
          scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5  //get top-position of target-element and set it as scroll target
        },1000,function()                  //scrolldelay: 1 seconds
        {
          location.hash = target;          //attach the hash (#jumptarget) to the pageurl
        });
      }

  $(document).ready(function()
  {
    $('a[href*="#"]').bind("click", jump); //get all hrefs
    return false;
  });

P.S:

注:

  • It includes a nice 5 pixels difference between header and target
  • 它包括一个漂亮的5像素的不同的头部和目标。
  • Scroll effect is not hard, rather smooth; Smooth Scrolling
  • 滚动效果不硬,相当平滑;平滑滚动