Programing

JavaScript를 트리거하는 링크를 클릭 할 때 웹 페이지가 맨 위로 스크롤되지 않도록하려면 어떻게합니까?

lottogame 2020. 6. 28. 18:25
반응형

JavaScript를 트리거하는 링크를 클릭 할 때 웹 페이지가 맨 위로 스크롤되지 않도록하려면 어떻게합니까?


다음과 같은 jQuery 또는 JavaScript 이벤트와 연결된 링크가있는 경우 :

<a href="#">My Link</a>

페이지가 맨 위로 스크롤되지 않도록하려면 어떻게합니까? 앵커에서 href 속성을 제거하면 페이지가 맨 위로 스크롤되지 않지만 링크를 클릭 할 수있는 것처럼 보이지 않습니다.


클릭 이벤트에 대한 기본 동작 (예 : 링크 대상으로 이동)이 발생하지 않도록해야합니다.

이를 수행하는 두 가지 방법이 있습니다.

옵션 1: event.preventDefault()

.preventDefault()핸들러로 전달 된 이벤트 오브젝트 메소드를 호출하십시오 . jQuery를 사용하여 핸들러를 바인딩하는 경우 해당 이벤트는의 인스턴스이며 jQuery.Event의 jQuery 버전이 .preventDefault()됩니다. addEventListener핸들러를 바인딩 하는 데 사용 하는 경우 Event및의 원시 DOM 버전이 .preventDefault()됩니다. 어느 쪽이든 당신이 원하는 것을 할 것입니다.

예 :

$('#ma_link').click(function($e) {
    $e.preventDefault();
    doSomething();
});

document.getElementById('#ma_link').addEventListener('click', function (e) {
    e.preventDefault();
    doSomething();
})

옵션 2 : return false;

jQuery에서 :

이벤트 핸들러에서 false를 반환하면 자동으로 event.stopPropagation () 및 event.preventDefault ()가 호출됩니다.

따라서 jQuery를 사용하면이 방법을 사용하여 기본 링크 동작을 방지 할 수 있습니다.

$('#ma_link').click(function(e) {
     doSomething();
     return false;
});

원시 DOM 이벤트를 사용하는 경우 HTML 5 사양에 따라이 동작이 적용되므로 최신 브라우저에서도 작동합니다. 그러나 이전 버전의 사양은 그렇지 않았으므로 이전 브라우저와의 최대 호환성이 필요한 경우 .preventDefault()명시 적으로 호출해야합니다 . 사양에 대한 자세한 내용은 event.preventDefault () 대 false 반환 (jQuery 없음)을 참조하십시오 .


#!대신 href를 설정할 수 있습니다#

예를 들어

<a href="#!">Link</a>

클릭하면 스크롤되지 않습니다.

조심해! 클릭하면 브라우저 기록에 항목이 계속 추가됩니다. 즉, 링크를 클릭하면 사용자의 뒤로 버튼이 이전 페이지로 이동하지 않습니다. 따라서 .preventDefault()접근 방식을 사용하거나 두 가지를 함께 사용하는 것이 좋습니다 .

여기에 이것을 보여주는 Fiddle이 있습니다 (스크롤 바가 나타날 때까지 브라우저를 아래로 긁으십시오) :
http://jsfiddle.net/9dEG7/


사양 대단원-왜 이것이 작동하는지 :

이 동작은 조각 식별자 탐색 섹션 의 HTML5 사양에 지정되어 있습니다. href가있는 링크로 "#"인해 문서가 맨 위로 스크롤 되는 이유 는이 동작이 빈 조각 식별자를 처리하는 방법으로 명시 적으로 지정 되었기 때문입니다.

2. fragid빈 문자열 인 경우 문서의 표시된 부분이 문서의 상단입니다

"#!"대신 href를 사용하면이 규칙을 피할 수 있기 때문에 간단하게 작동합니다. 느낌표에 대해 아무것도 마법이있다 - 그것은 이제까지 일치에 띄게 전형적인 fragid에 다른과 가능성이 있기 때문에 그냥 편리한 조각 식별자를하게 id하거나 name페이지에 요소의. 실제로 해시 뒤에는 거의 모든 것을 넣을 수 있습니다. 충분할 빈 문자열입니다하지 않습니다 만 fragids 단어 '최고', 또는 문자열이 일치하는 name또는 id페이지 요소의 속성.

보다 정확하게는, 우리는 단편 알고리즘 에서 문서표시된 부분 을 결정하기 위해 다음 알고리즘에서 8 단계로 넘어갈 수있는 단편 식별자가 필요합니다 .

  1. URL 파서 알고리즘을 URL에 적용하고 fragid를 결과 구문 분석 된 URL의 조각 구성 요소로 둡니다 .

  2. 경우 fragid빈 문자열은 다음 문서의 표시된 부분은 문서의 맨입니다; 여기서 알고리즘을 중지하십시오.

  3. fragid bytespercent-decoding의 결과로 보자 fragid.

  4. decoded fragidUTF-8 디코더 알고리즘을 적용한 결과를 보자 fragid bytes. UTF-8 디코더에서 디코더 오류가 발생하면 디코더를 중단하고 대신 레이블이 지정된 단계로 이동하십시오 no decoded fragid.

  5. DOM에 정확히 동일한 ID를 가진 decoded fragid요소가있는 경우 트리 순서의 첫 번째 요소는 문서의 표시된 부분입니다. 여기서 알고리즘을 중지하십시오.

  6. No decoded fragid: If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  7. If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.

  8. Otherwise, there is no indicated part of the document.

As long as we hit step 8 and there is no indicated part of the document, the following rule comes into play:

If there is no indicated part ... then the user agent must do nothing.

which is why the browser doesn't scroll.


An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.


Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this

<a href="javascript:;">Link Title</a>

When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.


You should change the

<a href="#">My Link</a>

to

<a href="javascript:;">My Link</a>

This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.

I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();


Try this:

<a href="#" onclick="return false;">My Link</a>

If you can simply change the href value, you should use:

<a href="javascript:void(0);">Link Title</a>

Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for href="#" links.

<script type="text/javascript">
    /* Stop page jumping when links are pressed */
    $('a[href="#"]').live("click", function(e) {
         return false; // prevent default click action from happening!
         e.preventDefault(); // same thing as above
    });
</script>

Link to something more sensible than the top of the page in the first place. Then cancel the default event.

See rule 2 of pragmatic progressive enhancement.


Also, you can use event.preventDefault inside onclick attribute.

<a href="#" onclick="event.preventDefault(); doSmth();">doSmth</a>

No need to write exstra click event.


You can simply write like this also:-

<a href="#!" onclick="function()">Delete User</a>

When calling the function, follow it by return false example:

<input  type="submit" value="Add" onclick="addNewPayment();return false;">

Create a page which contains two links- one at the top and one at the bottom. On clicking the top link, the page has to scroll down to the bottom of the page where bottom link is present. On clicking the bottom link, the page has to scroll up to the top of the page.


<a onclick="yourfunction()">

this will work fine . no need to add href="#"


You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.

Removing position: absolute; top: -9999px;, for display: none; might help.


For Bootstrap 3 for collapse, if you don't specify data-target on the anchor and rely on href to determine the target, the event will be prevented. If you use data-target you'll need to prevent the event yourself.

<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#demo">Collapse This</button>

<div id="demo" class="collapse"> 
<p>Lorem ipsum dolor sit amet</p>
</div>

참고URL : https://stackoverflow.com/questions/1601933/how-do-i-stop-a-web-page-from-scrolling-to-the-top-when-a-link-is-clicked-that-t

반응형