프로그래밍 방식으로 앵커 태그로 스크롤합니다
-
06-07-2019 - |
문제
다음 코드를 고려하십시오.
<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content
코드를 통해 페이지의 적절한 영역으로 스크롤하기 위해 "goto label2"링크를 클릭하는 방법이 있습니까?
편집하다: 허용 가능한 대안은 이미 내 페이지에 존재하는 고유 한 ID가있는 요소로 스크롤하는 것입니다. 이것이 실행 가능한 솔루션이라면 앵커 태그를 추가 할 것입니다.
해결책
이 JS는 일반적으로 요소에 ID를 넣으면 일반적으로 나에게 잘 작동했습니다.
document.getElementById('MyID').scrollIntoView(true);
이것은 컨텐츠가 보이도록 스크롤 가능한 div 등을 배치하기 때문에 좋습니다.
다른 팁
JavaScript 사용 :
window.location.href = '#label2';
서버/코드에서 수행 해야하는 경우이 JavaScript를 방출하고 해당 페이지의 시작 스크립트로 등록 할 수 있습니다.
서버 측에서 앵커로 이동하면 예제는 C#입니다.
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
나는 이것이 효과가 있다고 생각한다 :
window.location="<yourCurrentUri>#label2";
해결책
document.getElementById('MyID').scrollIntoView(true);
거의 모든 브라우저에서 잘 작동하는 반면, 일부 브라우저 나 일부 모바일 (일부 BlackBerry 버전)에서 "Scrollintoview"기능이 인식되지 않으므로이 솔루션을 고려할 것임을 알았습니다. :
window.location.href = window.location.protocol + "//" + window.location.host +
window.location.pathname + window.location.search +
"#MyAnchor";
요소가 앵커 태그 인 경우 다음을 수행 할 수 있어야합니다.
document.getElementsByName('label2')[0].focus();
no "#"Window.location.hash를 사용할 때
예를 들어 이름이 추가 된 이름으로 새 URL을 열 수 있습니다. http://www.example.com/mypage.htm#label2
JavaScript에서
location.href = location.href + '#label2';
제휴하지 않습니다 StackOverflow