source

앵커 링크를 연결된 위치의 일부 픽셀 위로 이동합니다.

manysource 2023. 9. 17. 13:18

앵커 링크를 연결된 위치의 일부 픽셀 위로 이동합니다.

이 질문을/검색하는 가장 좋은 방법을 모르겠습니다.

앵커 링크를 클릭하면 페이지의 해당 섹션으로 이동하고 페이지 맨 위에 링크된 영역이 표시됩니다.앵커 링크를 통해 해당 페이지로 보내주시면 좋겠는데 상단에 자리가 있으면 좋겠습니다.마찬가지로, VERY TOP에 있는 링크드 투 파트로 보내지 않았으면 좋겠고, 100픽셀 정도의 공간이 있으면 좋겠습니다.

이게 말이 됩니까?가능한가요?

코드를 표시하도록 편집됨 - 앵커 태그일 뿐입니다.

<a href="#anchor">Click me!</a>

<p id="anchor">I should be 100px below where I currently am!</p>
window.addEventListener("hashchange", function () {
    window.scrollTo(window.scrollX, window.scrollY - 100);
});

이렇게 하면 브라우저가 닻으로 점프하는 작업을 수행할 수 있고 그 위치를 사용하여 상쇄할 수 있습니다.

편집 1:

@erb에서 지적한 바와 같이 해시가 변경되는 동안 페이지에 있는 경우에만 작동합니다.에 a여를a으로 들어가기#something이미 URL에 있는 코드가 위 코드와 함께 작동하지 않습니다.다음은 이를 처리하기 위한 다른 버전입니다.

// The function actually applying the offset
function offsetAnchor() {
    if(location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).

하려면 : jQuery 하려면 할 를 하려면 할 를 window.addEventListener와 함께$(window).on요 @고마워요 @Neon.

편집 2:

Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ ΔΔ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ ΔΔ Δhashchange오프셋을 강제로 적용하는 이벤트.

이 솔루션은 @Mave에서 제안한 내용을 매우 약간 수정한 버전이며 단순화를 위해 jQuery selector를 사용합니다.

// The function actually applying the offset
function offsetAnchor() {
  if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
  }
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
  // Click events are captured before hashchanges. Timeout
  // causes offsetAnchor to be called after the page jump.
  window.setTimeout(function() {
    offsetAnchor();
  }, 0);
});

// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);

이 예제의 JSFiddle은 다음과 같습니다.

이에 대한 2020년 답은 다음과 같습니다.

#anchor {
  scroll-margin-top: 100px;
}

그것이 널리 지지를 받고 있기 때문입니다!

CSS로만 작업하면 고정 요소에 패딩을 추가할 수 있습니다(위의 솔루션에서와 같이). 불필요한 공백을 방지하기 위해 같은 높이의 음의 여백을 추가할 수 있습니다.

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

어떤 경우에도 이것이 최선의 해결책인지는 잘 모르겠지만, 저에게는 잘 통합니다.

더욱 뛰어난 솔루션:

<p style="position:relative;">
    <a name="anchor" style="position:absolute; top:-100px;"></a>
    I should be 100px below where I currently am!
</p>

을 .<a>상대적으로 위치한 객체의 내부에 절대 위치를 지정하는 태그입니다.

페이지를 입력할 때 또는 페이지 내의 해시 변경을 통해 작동합니다.

이것은 jQuery 없이 그리고 페이지 로드에서 작동합니다.

(function() {
    if (document.location.hash) {
        setTimeout(function() {
            window.scrollTo(window.scrollX, window.scrollY - 100);
        }, 10);
    }
})();

베스트 솔루션

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

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

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

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

이 순수한 CSS 솔루션은 저에게 적합합니다.

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

여기서 찾았어요 -> https://www.wikitechy.com/tutorials/javascript/offsetting-an-html-anchor-to-adjust-for-fixed-header

다음은 fiddle입니다: https://jsfiddle.net/e8o2p3az/

이 코드를 사용해 보십시오. 링크를 클릭하면 이미 부드러운 애니메이션이 나옵니다.

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

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top - 100
    }, 500);
});

를 ' 순수 CSS를에 한 의 를 에서 ' 해야 를 해야 를 에 한 padding-top, 이렇게 하면 요소는 여전히 창 상단에 위치하지만 뷰 포트 상단에서 약간 떨어진 곳에 위치하는 으로 보입니다. 예를 들어 다음과 같습니다.

<a href="#link1">Link one</a>
<a href="#link2">Link two</a>

<div id="link1">
    The first.
</div>

<div id="link2">
    The second.
</div>

CSS:

div {
    /* just to force height, and window-scrolling to get to the elements.
       Irrelevant to the demo, really */
    margin-top: 1000px;
    height: 1000px;
}

#link2 {
    /* places the contents of the element 100px from the top of the view-port */
    padding-top: 100px;
}

JS Fiddle 데모.

일반 자바스크립트 접근법을 사용하는 방법:

function addMargin() {
    window.scrollTo(0, window.pageYOffset - 100);
}

window.addEventListener('hashchange', addMargin);

JS Fiddle 데모.

작동해야 합니다.

    $(document).ready(function () {
    $('a').on('click', function (e) {
        // e.preventDefault();

        var target = this.hash,
            $target = $(target);

       $('html, body').stop().animate({
        'scrollTop': $target.offset().top-49
    }, 900, 'swing', function () {
    });

        console.log(window.location);

        return false;
    });
});

.top-49를 앵커 링크에 맞게 변경하기만 하면 됩니다.

다음과 같은 명시적 앵커 이름을 사용하는 경우

<a name="sectionLink"></a>
<h1>Section<h1>

그러면 CSS에서 간단히 설정할 수 있습니다.

A[name] {
    padding-top:100px;
}

이것은 HREF 앵커 태그가 NAME 특성도 지정하지 않는 한 작동합니다.

에릭의 대답은 훌륭하지만, 시간 초과는 정말로 필요하지 않습니다.jQuery를 사용하는 경우 페이지가 로드될 때까지 기다리면 됩니다.그래서 코드를 다음과 같이 변경할 것을 제안합니다.

// The function actually applying the offset
function offsetAnchor() {
    if (location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
$(window).on("hashchange", function () {
    offsetAnchor();
});

// Let the page finish loading.
$(document).ready(function() {
    offsetAnchor();
});

이것은 또한 우리가 그 자의적인 요소를 제거할 수 있게 해줍니다.

저는 그냥 제 자신을 위한 쉬운 해결책을 찾았습니다.마진 상단이 15px였습니다.

HTML

<h2 id="Anchor">Anchor</h2>

CSS

h2{margin-top:-60px; padding-top:75px;}

가장 쉬운 해결책:

CSS

#link {
    top:-120px; /* -(some pixels above) */
    position:relative;
    z-index:5;
}

HTML

<body>
    <a href="#link">Link</a>
    <div>
        <div id="link"></div> /*this div should placed inside a target div in the page*/
        text
        text
        text
    <div>
</body>

Thomas 솔루션의 변형: CSS element > element selector는 여기서 편리할 수 있습니다.

CSS

.paddedAnchor{
  position: relative;
}
.paddedAnchor > a{
  position: absolute;
  top: -100px;
}

HTML

<a href="#myAnchor">Click Me!</a>

<span class="paddedAnchor"><a name="myAnchor"></a></span>

가 를 하면 가 인 의 합니다 로 100px 의 의 위 합니다.paddedAnchor위치합니다.

브라우저에서 9 IE 에서 에서 9 됩니다 IE 되며 부터는 됩니다 에서 부터는 에서 .78에 , IE 7을 8 a<!DOCTYPE>신고해야 합니다.

CSS만 사용하고 이전에는 포괄되고 클릭할 수 없는 컨텐츠에 문제가 없는 경우(여기서 핵심은 포인터 이벤트: 없음):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

스타일에 맞게 배치:

.hash_link_tag{margin-top: -50px; position: absolute;}

이 을 별도의 이 에 사용합니다.div링크 앞에 태그를 지정합니다. 예:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

또는 에코 링크 태그에 이 php 코드를 사용합니다.

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

조금 늦었다는 것은 알지만, 부트스트랩의 스크롤스파이를 사용한다면 코드에 넣어야 할 매우 중요한 것을 발견했습니다.(http://getbootstrap.com/javascript/ #nonsspy)

이것 때문에 몇시간동안 미칠것같았어요.

스크롤 스파이에 대한 오프셋은 window.scrollY와 일치해야 합니다. 그렇지 않으면 다음 위험이 발생합니다.

  1. 스크롤할 때 이상한 깜박임 효과가 발생
  2. 앵커를 클릭하면 해당 구간에 착륙하지만 스크롤 스파이는 해당 구간 위에 있는 것으로 추정합니다.

 var body = $('body');
    body.scrollspy({
        'target': '#nav',
        'offset': 100 //this must match the window.scrollY below or you'll have a bad time mmkay
});

$(window).on("hashchange", function () {
        window.scrollTo(window.scrollX, window.scrollY - 100);
});

@Eric Olson 솔루션을 기반으로 제가 가고 싶은 앵커 요소를 포함하도록 조금만 수정하면 됩니다.

// Function that actually set offset
function offsetAnchor(e) {
    // location.hash.length different to 0 to ignore empty anchor (domain.me/page#)
    if (location.hash.length !== 0) {
        // Get the Y position of the element you want to go and place an offset
        window.scrollTo(0, $(e.target.hash).position().top - 150);
    }
}

// Catch the event with a time out to perform the offset function properly
$(document).on('click', 'a[href^="#"]', function (e) {
    window.setTimeout(function () {
        // Send event to get the target id later
        offsetAnchor(e);
    }, 10);
});

저도 똑같은 문제가 있습니다.나는 navpositive pixed를 가지고 있고 navpositive 아래에서 앙코르를 시작하기를 원합니다.의의 window.addEventListener...나는 내 페이지를 설정했기 때문에 나를 위해 일하지 않습니다.scroll-behavior:smooth그래서 그것은 오프셋 대신 스크롤을 앙코르로 설정했습니다.setTimeout()스크롤을 끝까지 하기에 시간이 충분하지만 여전히 좋아 보이지 않는 경우 작업합니다.그래서 나의 해결책은 앙코르에 절대 디브를 추가하는 것이었습니다.height:[the height of the nav]그리고.bottom:100%맨됩니다. 이 경우 앙코르 요소의 맨 위에서 분할되어 앙코르를 스크롤할 위치에서 시작합니다.이제 내가 하는 일은 앙코르 링크를 이 절대 디브와 워든으로 설정하는 것뿐입니다 :)

html,body{
    margin:0;
    padding:0;
    scroll-behavior:smooth;
}

nav {
    height:30px;
    width:100%;
    font-size:20pt;
    text-align:center;
    color:white;
    background-color:black;
    position:relative;
}

#my_nav{
    position:fixed;
    z-index:3;
}
#fixer_nav{
    position:static;
}

#angkor{
    position:absolute;
    bottom:100%;
    height:30px;
}
<nav id="my_nav"><a href="#angkor">fixed position nav<a/></nav>
<nav id="fixer_nav"></nav>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.
</p>

<nav><div id="angkor"></div>The angkor</nav>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.

</p>

저는 비슷한 문제에 직면하고 있었고 다음 코드를 사용하여 해결했습니다.

$(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);
        var desiredHeight = $(window).height() - 577;
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - desiredHeight
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });

저도 같은 문제가 있었는데, JS의 CSS가 없는 정말 빠르고 간단한 해결책이 있습니다."와 같은 ID를 가진 별도의 스타일 없는 디바를 만들기만 하면 됩니다.aboutMeAnchor그리고 실제로 착륙하고 싶은 구간보다 훨씬 위에 위치시키기만 하면 됩니다.

이것 또한 좋은 해결책입니다. 위 지서기기e지eavediv를 이시켜 주세요;서이를에요게이요에서ae를e게k;

<div class="destination" id="link"></div> /**Needs to be above the destination**/

.destination {
    position:absolute;
    z-index:-1;
    left:0;
    margin-top:-100px;/* height of nav*/
}

가 있었던 인 는 에게 가 은 입니다 하는 를 을 입니다 하는 를 는 은 ::before스크롤할 디브로 이동합니다.이렇게 하면 요소가 공백을 추가하고 앵커 링크가 이 공백 맨 위로 스크롤됩니다.예를 들어,

#anchor::before {
  content: "";
  display: block;
  height: 60px;
}

앵커 링크 대상의 스크롤 위치에 대해 기본적으로 동일한 문제라고 생각하는 것에 대해 놀라운 해결책을 발견했습니다.

다음과 같이 북마크 돔 요소 바로 위에 머리글을 표시하는 하위 섹션이 있는 긴 문서를 보여주는 페이지가 있습니다.

<div class = "TB_BookMark"
        id = "someId"  
></div>
<h3 class="TB">Section 1</h3>

이 아이디어는 사용자가 측면 창에서 링크를 클릭하여 문서의 하위 섹션으로 이동할 수 있다는 것입니다.첫 번째 링크는 페이지 시작까지 창을 스크롤해야 합니다.위의 북마크-div의 내용은 비어 있으므로 페이지에서 공백을 가져가지 않아야 하며, 따라서 첫 번째 링크로 이동하면 페이지의 처음으로 이동해야 합니다.

문제는 첫 번째 링크를 클릭하면 페이지가 스크롤되어 첫 번째 섹션 헤더가 눈에 보이는 영역의 맨 위에 빈 공간이 없이 바로 표시된다는 것이었습니다.즉, 페이지가 위에서 조금 아래로 스크롤 된 것입니다.반면 페이지를 로드하거나 다시 로드할 때 첫 번째 섹션 헤더 위에 여백이 표시됩니다.

저는 이것이 원래 질문이 설명하는 것과 같은 문제라고 생각합니다.페이지 맨 처음으로 스크롤할 수 있는 첫 번째 링크를 얻을 방법이 없는 것입니다.

문제는 페이지를 로드할 때 표시되는 내용이 첫 번째 링크를 클릭할 때 표시되는 내용과 다르다는 것입니다.첫 번째 머리글 위에 공백 여백이 더 이상 없거나, 페이지를 로드하거나 다시 로드할 때 여백이 너무 크게 나타나는 경우에는 보기 좋지 않습니다.

이것이 작동하게 된 방법은 다음과 같은 CSS입니다.

.TB_Bookmark
{ border:solid 0px    Transparent;  /* Does NOT do what I want. */
  border:solid 0.01px Transparent;  /* Does what I want. */
}

h3.TB
{ margin-top:12px;
  margin-bottom:12px;
}

body
{ margin-top: 0px;
}

작동하지 않는 것에 대한 예시로 남겨둔 첫 번째 경계 정의를 제외하고는 위의 모든 것이 작동하기 위해 필요했습니다.두 번째 경계 정의는 물론 첫 번째 경계 정의를 무시하므로 효력이 발생합니다.

"border: solid 0.01px;"는 작동하지만 "border: solid 0px;"는 왜 작동하는지 이해할 수 없습니다.0과 0.01 사이에는 큰 차이가 없을 것입니다.이 솔루션은 Chrome과 Firefox에서 모두 작동하며 "border:solid 0px;"를 사용하면 둘 다 작동하지 않습니다.

<a href="#anchor">Click me!</a>

<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>

언급URL : https://stackoverflow.com/questions/17534661/make-anchor-link-go-some-pixels-above-where-its-linked-to