programing

jquery를 사용하여 페이지의 특정 위치로 스크롤하려면 어떻게 해야 합니까?

fastcode 2023. 8. 8. 23:56
반응형

jquery를 사용하여 페이지의 특정 위치로 스크롤하려면 어떻게 해야 합니까?

jQuery를 사용하여 페이지의 특정 위치로 스크롤할 수 있습니까?

스크롤하려는 위치에 다음이 있어야 합니까?

<a name="#123">here</a>

아니면 특정 DOM ID로 이동할 수 있습니까?

jQueryScroll 플러그인

이것은 jquery로 태그된 질문이기 때문에, 이 라이브러리는 부드러운 스크롤을 위한 매우 좋은 플러그인을 가지고 있다고 말해야 합니다. http://plugins.jquery.com/scrollTo/ 에서 찾을 수 있습니다.

설명서에서 발췌한 내용:

$('div.pane').scrollTo(...);//all divs w/class pane

또는

$.scrollTo(...);//the plugin will take care of this

스크롤을 위한 사용자 정의 jQuery 기능

당신은 당신의 사용자 정의 스크롤 jquery 함수를 정의함으로써 매우 가벼운 접근법을 사용자 정의 스크롤 jquery 함수

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

다음과 같이 사용합니다.

$('#your-div').scrollView();

페이지 좌표로 스크롤

애니메이트html그리고.body와의 요소.scrollTop또는scrollLeft특성

$('html, body').animate({
    scrollTop: 0,
    scrollLeft: 300
}, 1000);

플레인 자바스크립트

스크롤링하기window.scroll

window.scroll(horizontalOffset, verticalOffset);

요약하자면, window.location을 사용합니다.ID를 사용하여 요소로 이동할 해시

window.location.hash = '#your-page-element';

HTML로 직접(접근성 향상)

<a href="#your-page-element">Jump to ID</a>

<div id="your-page-element">
    will jump here
</div>

네, 일반 자바스크립트로도 꽤 쉽습니다.요소에 ID를 지정한 다음 "책갈피"로 사용할 수 있습니다.

<div id="here">here</div>

사용자가 링크를 클릭할 때 해당 링크를 스크롤하려면 Try-and-True 방법을 사용하면 됩니다.

<a href="#here">scroll to over there</a>

프로그래밍 방식으로 수행하려면,

document.getElementById("here").scrollIntoView()

플러그인을 사용할 필요가 없으므로 다음과 같이 수행할 수 있습니다.

var divPosition = $('#divId').offset();

그런 다음 문서를 특정 DOM으로 스크롤하는 데 사용합니다.

$('html, body').animate({scrollTop: divPosition.top}, "slow");

다음은 순수 자바스크립트 버전입니다.

location.hash = '#123';

자동으로 스크롤됩니다."#" 접두사를 추가해야 합니다.

일반 Javascript:

window.location = "#elementId"
<div id="idVal">
    <!--div content goes here-->
</div>
...
<script type="text/javascript">
     $(document).ready(function(){
         var divLoc = $('#idVal').offset();
         $('html, body').animate({scrollTop: divLoc.top}, "slow");
     });
</script>

이 예는 특정 구분(예: 이 경우 'idVal')을 찾는 방법을 참조하십시오.Ajax를 통해 이 페이지에 열리는 후속 div/테이블이 있는 경우 고유 div를 할당하고 스크립트를 호출하여 각 div 콘텐츠의 특정 위치로 스크롤할 수 있습니다.

이것이 유용하기를 바랍니다.

<script type="text/javascript">
    $(document).ready(function(){
        $(".scroll-element").click(function(){
            $('html,body').animate({
                scrollTop: $('.our_companies').offset().top
            }, 1000);

            return false;
        });
    })
</script>

사용해 보세요.

<div id="divRegister"></div>

$(document).ready(function() {
location.hash = "divRegister";
});

다음은 @juraj-blahunka의 경량 접근 방식의 변형입니다.이 함수는 컨테이너가 문서라고 가정하지 않고 항목이 보이지 않는 경우에만 스크롤됩니다.불필요한 바운스를 방지하기 위해 애니메이션 큐도 비활성화됩니다.

$.fn.scrollToView = function () {
    return $.each(this, function () {
        if ($(this).position().top < 0 ||
            $(this).position().top + $(this).height() > $(this).parent().height()) {
            $(this).parent().animate({
                scrollTop: $(this).parent().scrollTop() + $(this).position().top
            }, {
                duration: 300,
                queue: false
            });
        }
    });
};

jquery.easing.min.js 사용, 고정 IE 콘솔 오류 포함

HTML

<a class="page-scroll" href="#features">Features</a>
<section id="features" class="features-section">Features Section</section>


        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="js/jquery.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Scrolling Nav JavaScript -->
        <script src="js/jquery.easing.min.js"></script>

제이쿼리

//jQuery to collapse the navbar on scroll, you can use this code with in external file with name scrolling-nav.js
        $(window).scroll(function () {
            if ($(".navbar").offset().top > 50) {
                $(".navbar-fixed-top").addClass("top-nav-collapse");
            } else {
                $(".navbar-fixed-top").removeClass("top-nav-collapse");
            }
        });
        //jQuery for page scrolling feature - requires jQuery Easing plugin
        $(function () {
            $('a.page-scroll').bind('click', function (event) {
                var anchor = $(this);
                if ($(anchor).length > 0) {
                    var href = $(anchor).attr('href');
                    if ($(href.substring(href.indexOf('#'))).length > 0) {
                        $('html, body').stop().animate({
                            scrollTop: $(href.substring(href.indexOf('#'))).offset().top
                        }, 1500, 'easeInOutExpo');
                    }
                    else {
                        window.location = href;
                    }
                }
                event.preventDefault();
            });
        });

사용할 수 있습니다.scroll-behavior: smooth;Javascript 없이 이 작업을 완료하기 위해

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

언급URL : https://stackoverflow.com/questions/1586341/how-can-i-scroll-to-a-specific-location-on-the-page-using-jquery

반응형