我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。


当前回答

对于现代浏览器,只需将CSS3:target选择器添加到页面。这将自动应用于所有的锚。

:target {
    display: block;    
    position: relative;     
    top: -100px;
    visibility: hidden;
}

其他回答

再加上Ziav的回答(感谢Alexander Savin),我需要使用老式的<a name="…">…</a> as we're using <div id="…">…</div>用于代码中的另一个目的。我在使用display: inline-block时遇到了一些显示问题——每个<p>元素的第一行都略微右缩进(在Webkit和Firefox浏览器上都是如此)。我最终尝试了其他的显示值和display: table-标题对我来说非常适合。

.anchor {
  padding-top: 60px;
  margin-top: -60px;
  display: table-caption;
}

你可以只使用CSS而不需要任何javascript。

给你的锚一个类:

<a class="anchor" id="top"></a>

然后,通过将锚定位为块元素并相对定位,您可以将锚定位在比它在页面上实际出现的位置更高或更低的偏移量。-250px将锚点向上定位250px

a.anchor {
    display: block;
    position: relative;
    top: -250px;
    visibility: hidden;
}

我也在寻找这个问题的解决方案。对我来说,这很简单。

我有一个列表菜单与所有的链接:

<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>

下面是标题。

<h3>one</h3>
<p>text here</p>

<h3>two</h3>
<p>text here</p>

<h3>three</h3>
<p>text here</p>

<h3>four</h3>
<p>text here</p>

现在,因为我在页面顶部有一个固定的菜单,我不能让它去我的标签,因为它会在菜单后面。

相反,我在标签中放入了一个span标签,并带有正确的id。

<h3><span id="one"></span>one</h3>

现在使用2行CSS来正确定位它们。

h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}

更改顶部值以匹配固定标题的高度(或更多)。 现在我认为这也适用于其他元素。

我也曾面临过类似的问题,不幸的是,在实施了上述所有解决方案后,我得出了以下结论。

我的内部元素有一个脆弱的CSS结构和实现位置相对/绝对发挥,完全打破了页面设计。 CSS不是我的强项。

我写了这个简单的滚动js,它解释了由于标题引起的偏移,并将div重新定位到下面大约125像素。请用你认为合适的。

HTML

<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->

JavaScript

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
&& location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});

点击这里查看实时实现。

由于这是表示的问题,纯CSS解决方案将是理想的。然而,这个问题是在2012年提出的,尽管已经提出了相对定位/负边际的解决方案,但这些方法看起来相当俗气,会产生潜在的流量问题,并且不能动态响应DOM /视口的变化。

考虑到这一点,我相信使用JavaScript仍然是(2017年2月)最好的方法。下面是一个香草- js解决方案,它将响应锚点点击并在加载时解析页面哈希(参见JSFiddle)。如果需要动态计算,请修改. getfixedoffset()方法。如果您正在使用jQuery,这里有一个经过修改的解决方案,具有更好的事件委托和平滑滚动。

(function(document, history, location) {
  var HISTORY_SUPPORT = !!(history && history.pushState);

  var anchorScrolls = {
    ANCHOR_REGEX: /^#[^ ]+$/,
    OFFSET_HEIGHT_PX: 50,

    /**
     * Establish events, and fix initial scroll position if a hash is provided.
     */
    init: function() {
      this.scrollToCurrent();
      window.addEventListener('hashchange', this.scrollToCurrent.bind(this));
      document.body.addEventListener('click', this.delegateAnchors.bind(this));
    },

    /**
     * Return the offset amount to deduct from the normal scroll position.
     * Modify as appropriate to allow for dynamic calculations
     */
    getFixedOffset: function() {
      return this.OFFSET_HEIGHT_PX;
    },

    /**
     * If the provided href is an anchor which resolves to an element on the
     * page, scroll to it.
     * @param  {String} href
     * @return {Boolean} - Was the href an anchor.
     */
    scrollIfAnchor: function(href, pushToHistory) {
      var match, rect, anchorOffset;

      if(!this.ANCHOR_REGEX.test(href)) {
        return false;
      }

      match = document.getElementById(href.slice(1));

      if(match) {
        rect = match.getBoundingClientRect();
        anchorOffset = window.pageYOffset + rect.top - this.getFixedOffset();
        window.scrollTo(window.pageXOffset, anchorOffset);

        // Add the state to history as-per normal anchor links
        if(HISTORY_SUPPORT && pushToHistory) {
          history.pushState({}, document.title, location.pathname + href);
        }
      }

      return !!match;
    },

    /**
     * Attempt to scroll to the current location's hash.
     */
    scrollToCurrent: function() {
      this.scrollIfAnchor(window.location.hash);
    },

    /**
     * If the click event's target was an anchor, fix the scroll position.
     */
    delegateAnchors: function(e) {
      var elem = e.target;

      if(
        elem.nodeName === 'A' &&
        this.scrollIfAnchor(elem.getAttribute('href'), true)
      ) {
        e.preventDefault();
      }
    }
  };

  window.addEventListener(
    'DOMContentLoaded', anchorScrolls.init.bind(anchorScrolls)
  );
})(window.document, window.history, window.location);