質問

HTMLページに非スクロールヘッダーがある場合、上部に固定されていて、定義された高さを持っています。

URLアンカーを使用する方法はありますか( #fragment パート)ブラウザをページの特定のポイントにスクロールするが、固定要素の高さを尊重する 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    |
| ...                             |      | ...                             |
+---------------------------------+      +---------------------------------+
役に立ちましたか?

解決

同じ問題がありました。パディングトップ値としてトップバーの高さを持つアンカー要素にクラスを追加することでそれを解決しました。

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

そして、単にCSS:

.anchor { padding-top: 90px; }

他のヒント

新しいクラスを設定できない、または設定したくない場合は、固定高さを追加します ::before 擬似要素へ :target CSSの擬似クラス:

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

または、関連するページをスクロールします :target jqueryで:

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

私はこのアプローチを使用します:

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

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

各ターゲットの前に見えない要素を追加します。 IE8+で動作します。

ここにもっと解決策があります:http://nicolasgallagher.com/jump-links-and-viewport-positing/

公式ブートストラップ採用回答:

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

クレジット

マージ

私がこの問題を処理するために見つけた最良の方法は(65pxを固定要素の高さに置き換えます):

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

使用したくない場合 目標 セレクターあなたはこの方法でそれを行うこともできます:

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

注:この例は、ターゲット要素が親とは異なるバックガウンド色を持っている場合、機能しません。例えば:

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

この場合、私のターゲット要素の緑色は、65pxで親の赤い要素を上書きします。この問題を処理するための純粋なCSSソリューションは見つかりませんでしたが、別の背景色がない場合は、このソリューションが最適です。

提案されたソリューションの一部はフラグメントリンクに対して機能します(=ハッシュリンク) 以内に 同じページ(下にスクロールするメニューリンクのように)は、入ってくるフラグメントリンクを使用するときに現在のクロムで機能しないことがわかりました 他のページから.

したがって、www.mydomain.com/page.html#fooをゼロから電話してください いいえ 指定されたCSSソリューションまたはJSソリューションのいずれかで、現在のクロムのターゲットを相殺します。

aもあります jQueryバグレポート 問題の詳細を説明します。

解決

私がこれまでに見つけた唯一のオプションは、Chromeで実際に機能することです。

// 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);
    }
}

まとめ

JS遅延ソリューションがないと、おそらくFirefox、つまり、Safariで動作しますが、Chromeでは機能しません。

Chrome/Safari/Firefoxの場合、 display: block そして、次のようなオフセットを補うために負のマージンを使用してください。

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

例を参照してください http://codepen.io/swed/pen/rrzbjo

jqueryでこれを行うことができます:

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

あなたはこれを試すことができます:

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

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

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

トップパディング値をヘッダーの実際の高さに設定します。これにより、ヘッダーの上部にわずかな余分なギャップが導入されますが、ユーザーがアンカーにジャンプしてスクロールアップした場合にのみ表示されます。私は今自分のサイトのソリューションを作りましたが、ページの上部に小さな固定バーしかなく、高すぎるものはありません。

わたしにはできる:

アンカーへのHTMLリンク:

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

HTMLアンカー:

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

CSS:

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

上記の「アンカー:前」の方法を使用して、CSSとHTMLで簡単に動作します。 DIVの間に大きなパディングを作成しないため、最善を尽くすと思います。

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

ページ上の最初のdivには機能しないようですが、その最初のdivにパディングを追加することでそれに対抗できます。

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

これが機能するフィドルです: http://jsfiddle.net/frphe/24/

@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();
      }
  };
html {
  scroll-padding-top: 70px; /* height of sticky header */
}

から: https://css-tricks.com/fixed-headers-on-page-links-and-overloppycontent-oh-my/

それは私の純粋主義者の心にはややハッキーだと感じていますが、CSSのみのソリューションとして、アクティブな固定要素にパディングを追加できます。 :target セレクタ:

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>

私は使わなければならないことがわかりました 両方とも mutttenxd'砂 バダバムCSSソリューションは一緒になっています。1つ目はChromeでは機能せず、2つ目は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>
...

私が最もきれいであると思う方法は、次のものです。

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

ブックマークされたアンカーがFAQページのセクションヘッダーであったため、ここや他の場所で多くの答えに多くの問題がありました。だから私は投稿すると思った。

私がやったことは、いくつかの解決策の複合でした。

  1. CSS:

    .bookmark {
        margin-top:-120px;
        padding-bottom:120px; 
        display:block;
    }
    

ここで、「120px」は固定ヘッダーの高さ(たぶんマージンに加えて)です。

  1. ブックマークリンクHTML:

    <a href="#01">What is your FAQ question again?</a>
    
  2. ブックマークされたコンテンツHTML:

    <span class="bookmark" id="01"></span>
    <h3>What is your FAQ question again?</h3>
    <p>Some FAQ text, followed by ...</p>
    <p>... some more FAQ text, etc ...</p>
    

この解決策の良いところは、です span 要素は隠されているだけでなく、本質的に崩壊し、コンテンツを埋めません。

このソリューションは、さまざまなリソースの盗品から来ているため、あまり信用することはできませんが、私の状況では私にとって最適でした。

実際の結果を見ることができます ここ.

として CSSスクロールスナップ仕様 ゲームに入ると、簡単に可能です scroll-margin-top 財産。現在、Chrome and Operaで実行されています(2019年4月)。また、Safari 11+はこれをサポートする必要がありますが、Safari 11で実行することはできませんでした。おそらく、人がそれを修正するのを待つ必要があります。

Codepenの例

body {
  padding: 0;
  margin: 0;
}

h1,
p {
  max-width: 40rem;
  margin-left: auto;
  margin-right: auto;
}
h1 {
  scroll-margin-top: 6rem; /* One line solution. :-) */
}
.header {
  position: sticky;
  top: 0;
  background-color: red;
  text-align: center;
  padding: 1rem;
}
.header .scroll {
  display: block;
  color: white;
  margin-bottom: 0.5rem;
}
.header .browsers {
  color: black;
  font-size: 0.8em;
}
<header class="header">
  <a class="scroll" href="#heading">Scroll to heading</a>
  <span class="browsers" >Chrome 69+, Opera 56+ and Safari 11+ only</span>
</header>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<h1 id="heading">What is Lorem Ipsum?</h1>
<p>
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
<p>
  

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent pulvinar eleifend dolor, in cursus augue interdum quis. Morbi volutpat pulvinar nisl et condimentum. Quisque elit lacus, egestas non ante sit amet, hendrerit commodo dui. Nunc ac sagittis dolor. Proin iaculis ante non est pharetra, et ullamcorper nisl accumsan. Aenean quis leo vel sapien eleifend aliquam. Pellentesque finibus dui ex, blandit tristique risus vestibulum vitae. Nam a quam ac turpis porta eleifend. Sed at hendrerit risus, ac efficitur ante. Aenean pretium justo feugiat condimentum consectetur. Etiam mattis urna id porta hendrerit.
</p>
<p>
Mauris venenatis quam sed egestas auctor. Fusce lacus eros, condimentum nec quam vel, malesuada gravida libero. Praesent vel sollicitudin justo. Donec mattis nisl id mauris scelerisque, quis placerat lectus scelerisque. Ut id justo a magna mattis luctus. Suspendisse massa est, pretium vel suscipit sit amet, iaculis at mi. Aenean vulputate ipsum non consectetur sodales. Proin aliquet erat nec mi eleifend, eu dapibus enim ultrices. Sed fringilla tortor ac rhoncus consectetur. Aliquam aliquam orci ultrices tortor bibendum facilisis.
</p>
<p>
Donec ultrices diam quam, non tincidunt purus scelerisque aliquam. Nam pretium interdum lacinia. Donec sit amet diam odio. Donec eleifend nibh ut arcu dictum, in vulputate magna malesuada. Nam id dignissim tortor. Suspendisse commodo, nunc sit amet blandit laoreet, turpis nibh rhoncus mi, et finibus nisi diam sed erat. Vivamus diam arcu, placerat in ultrices eu, porta ut tellus. Aliquam vel nisi nisi.
</p>
<p>
Integer ornare finibus sem, eget vulputate lacus ultrices ac. Vivamus aliquam arcu sit amet urna facilisis consectetur. Sed molestie dolor et tortor elementum, nec bibendum tortor cursus. Nulla ipsum nulla, luctus nec fringilla id, sagittis et sem. Etiam at dolor in libero pharetra consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse quis turpis non diam mattis varius. Praesent at gravida mi. Etiam suscipit blandit dolor, nec convallis lectus mattis vitae. Mauris placerat erat ipsum, vitae interdum mauris consequat quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
<p>
Nunc efficitur scelerisque elit. Integer ac massa ipsum. Cras volutpat nulla purus, quis molestie dolor iaculis eget. Maecenas ut ex nulla. Pellentesque sem augue, ornare ut arcu eu, porttitor consectetur orci. Aenean iaculis blandit quam, in efficitur justo sodales auctor. Vivamus dignissim pellentesque risus eget consequat. Pellentesque sit amet nisi in urna convallis egestas vitae nec mauris. 
</p>

jQueryを使用した最小限の侵入アプローチ:

リンク:

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

コンテンツ:

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

脚本:

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

アンカーリンククラスをリンクに割り当てることにより、他のリンク(アコーディオンやタブコントロールなど)の動作が影響を受けません。

質問はJavaScriptを望んでいませんが 他のより一般的な質問 これのために閉鎖されており、私はそこに答えることができませんでした。

インバウンドリンク、ページ上のリンクに機能するものが必要でした。これは、ページがヘッダーの高さの変更に応答できるようにJSで標的にすることができます。

HTML

<ul>
  <li><a href="#ft_who">Who?</a></li>
  <li><a href="#ft_what">What?</a></li>
  <li><a href="#ft_when">When?</a></li>
</ul>
...
<h2 id="ft_who" class="fragment-target">Who?</h2> 
...
<a href="#">Can I be clicked?</a>
<h2 id="ft_what" class="fragment-target">What?</h2>
...
<h2 id="ft_when" class="fragment-target">When?</h2> 

CSS

.fragment-target {
    display: block;
    margin-top: -HEADER_HEIGHTpx;
    padding-top: HEADER_HEIGHTpx;
    z-index: -1;
}

z-index: -1 フラグメントターゲットの上にある「パディングエリア」のリンクが、彼の回答で@muttenxdによってコメントされているように、まだクリック可能であることを許可します

IE 11、Edge 15+、Chrome 38+、FF 52+、またはSafari 9.1+でまだ問題は見つかりませんでした

私は上記の答えに運がありませんでした、そして、完璧に機能するこのソリューションを使用することになりました...

アンカーを設定する空白のスパンを作成します。

<span class="anchor" id="section1"></span>
<div class="section"></div>

次のクラスを適用します。

.anchor {
  display: block;
  height: 115px;       /* same height as header */
  margin-top: -115px;  /* same height as header */
  visibility: hidden;
}

このソリューションは、セクションに異なる色の背景がある場合でも機能します!で解決策を見つけました このリンク。

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

このコードはトリックを行う必要があります。ヘッダーバーの高さのために45pxを交換します。

編集:jQueryを使用することがオプションである場合、オフセット値セットでjquery.localscrollを使用することも成功しました。オフセットオプションは、jquery.scrolltoの一部であり、jquery.localscrollの上に構築されています。デモはこちらから入手できます。 http://demos.flesler.com/jquery/scrollto/ (2番目のウィンドウ、「オフセット」の下)

IEで機能する完全なjQueryソリューションは次のとおりです。

ナビゲーションバーの要素が次のようなものであると仮定します。

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

次の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) {

    });
}

使用して実装 :before 擬似要素が実際に座っていたポインターイベントをカバーしてブロックしていることに気付くまで、うまくいきました 以内に 擬似要素の領域。のようなものを使用します pointer-events: none:before または、アンカーに直接影響を与えませんでした。

私たちがやったことは、アンカーのポジショニングを絶対にし、固定領域のオフセット/高さになるように位置を調整することでした。

ポインターイベントをブロックせずにアンカーをオフセットします

.section-marker {

    position: absolute;
    top: -300px;
}

これの値は、これらの300px以内に該当する可能性のある要素をブロックしていないことです。欠点は、JavaScriptからその要素の位置をつかむ必要があるため、そのオフセットを考慮に入れる必要があるため、ロジックを調整する必要があることです。

これは、ナビゲーションをクリックするときに最終的に適切な場所に行くようにした方法です。ナビゲーションクリック用のイベントハンドラーを追加しました。次に、「Scrollby」を使用して、オフセットで上に移動できます。

var offset = 90;

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

数回のラインブレークでDIVを作成し、IDを与えた後、下に表示したいコードを配置しました。その後、リンクは画像の上のスペースに移動し、ヘッダーは邪魔になりなくなります。

<a href="#image">Image</a>
<div id="image"><br><br></div>
<img src="Image.png">

もちろん、ニーズに合わせてラインブレーク数を変更できます。これは私にとって完璧に機能しましたが、問題があるかどうかはわかりませんが、私はまだHTMLを学んでいます。

このスクリプトを使用しました

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top -140
    }, 1000);
});
// handle hashes when page loads
// <http://stackoverflow.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();
  }
});

何らかの理由で、提案された他のソリューションは実際に私のために機能しなかったため、この方法を使用しています。私は試したことを約束します。

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;
}

交換 セクション 必要に応じてクラスによって。

ソース: ジャンプリンクとビューポートの位置付け

  • Firefox 45およびChrome 52でテストしました。
  • ブートストラップバージョン:3.3.7

私を信じていない人のために、私は親切に解決策を備えたJSFiddleを準備しました: 解決

CSSトリックは回避策になります。すべてのシナリオで機能する適切なソリューションは、jQueryを使用して実装できます。

参照する https://codepen.io/pikeshmn/pen/mmxedz

アプローチ: 使用して固定NAVの高さを取得します document.getElementById( 'ヘッダー')。offseethスクロールをこの値にオフセットします。

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;
  });

PS:

  • ヘッダーとターゲットの間に5ピクセルの違いが含まれています
  • スクロール効果は難しくなく、滑らかです。滑らかなスクロール
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top