簡體   English   中英

使用錨點鏈接上的JavaScript平滑滾動

[英]Smooth scrolling using javascript on anchor link

我想在php程序中使用javascript進行平滑滾動 在此處輸入圖片說明 如圖所示,如果我從左側欄中單擊了客戶,那么我想使用javascript onclick函數進行平滑滾動,我該怎么辦?在這里,我通過了動態ID,我是從數據庫中獲取的

<div class="col-md-3 col-sm-12" >   

                                <ul data-spy="affix" data-offset-top="205" class="myclasss">
                                    <?php 
                                    foreach($var as $name) { ?>
                                        <a  id="#<?php echo $name['name'];?>" class="list-group-item" onclick="scrollFaq(this.id);"><?php echo $name['name'];?> </a><?php } ?> 


                                  </ul>
                            </div>      



                            <div class="col-md-9 col-sm-12 ">   
                                    <?php  $v1 = '';
                                       foreach($var as $data){
                                   ?>

                            <div class="faqHeader" id="<?php echo $data['name'];?>"> <?php echo $data['name'];?> </div>             
                                <div class="panel-group" ">
                                            <?php           
                                            foreach($data['data'] as $dat){ ?> 
                                    <div class="panel panel-default">
                                        <div class="panel-heading ">
                                            <h4 class="panel-title">
                                                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion"  href="#col<?php
                                                echo $v1;?>" ><?php echo $dat['questions'];?> </a>
                                            </h4>
                                        </div>
                                        <div id="col<?php echo $v1;?>" class="panel-collapse collapse ">
                                            <div class="panel-body">
                                                <?php echo $dat['answer'];?>
                                            </div>
                                        </div>
                                    </div>



<script>
function scrollFaq(str){
alert(str);
}
</script>

嘗試這個 :

function scrollFaq(str){
    $('html,body').animate({scrollTop:$("#"+str).offset().top}, 500);
}

確保像這樣將這個ID分配給div中的div

<div class="col-md-9 col-sm-12 ">   
    <?php  $v1 = '';
        foreach($var as $data){
        ?>

        <div class="faqHeader" id="<?php echo $data['name']; ?>"> 
            <?php echo $data['name'];?> 
        </div>
  <?php } ?>
</div>

一個簡單的示例,說明如何無需使用jQuery就可以平滑滾動到元素。

<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Smooth scroll to element without jQuery</title>
        <script>

            function scrollFaq( event ){
                event.preventDefault();
                /*
                    Current position and target position
                    Note: I used `dataset.name` rather than
                    adding the desired ID as an argument to this
                    function ~ see html below
                */
                var cp=event.target.offsetTop;
                var fp=document.getElementById( event.target.dataset.name ).offsetTop;
                /*
                    increase step for larger jump per time period
                    increase time for longer animation
                */
                var step=100;
                var time=10;

                /* initial step */
                var pos  = cp + step;

                /* self-executing anonymous function */
                (function(){
                    var t;
                    /* increment the position */
                    pos+=step;

                    /* clear the timer if we are at the correct location */
                    if( pos >= fp ){
                        clearTimeout( t );
                        return false;
                    }
                    /* do the actual scroll */
                    window.scrollTo( 0, pos );

                    /* re-run the function until we reach the correct location */
                    t=setTimeout( arguments.callee, time );
                })();
            }
        </script>
        <style>
            .large{
                margin:0 0 100rem 0;
                border:1px solid black;
                display:block;
                height:100rem;
                font-size:1.5rem;
            }
            a{
                display:block;
                clear:none;
                margin:0 1rem 1rem 1rem;
                width:200px;
                padding:1rem;
                font-size:1rem;
                background:blue;
                color:white;
                border:1px solid black;
            }
        </style>
    </head>
    <body>
    <?php
        $names=array(/* some random names */
            'marilyn','jane','rita','sue','bob','customer','worker'
        );
        foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
            echo "<a href='#' data-name='$name' onclick=\"scrollFaq( event );\">$name</a>";
        }
        foreach( $names as $name ){
            echo "<div id='$name' class='large'>$name</div>";
        }
    ?>
    </body>
</html>

或者,一種更好的方法,該方法不涉及內聯事件處理程序,而現在使用原始的className。

無需在任何循環中都聲明Javascript函數-確實這樣做是不正確的。 在頁面頂部聲明功能,並按如下所示進行相應調用。 您可以復制任何一個示例,然后保存並運行以查看滾動效果-然后適應您的“用例”就很簡單了

<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Smooth scroll to element without jQuery</title>
        <script>
            function scrollFaq( event ){
                event.preventDefault();
                /*
                    Current position and target position
                    Note: I used `dataset.name` rather than
                    adding the desired ID as an argument to this
                    function ~ see html below
                */
                var cp=event.target.offsetTop;
                var fp=document.getElementById( event.target.dataset.name ).offsetTop;
                /*
                    increase step for larger jump per time period
                    increase time for longer animation
                */
                var step=50;
                var time=10;

                /* initial step */
                var pos  = cp + step;
                var t;

                (function(){
                    /* increment the position */
                    pos+=step;

                    /* clear the timer if we are at the correct location */
                    if( pos >= fp ){
                        clearTimeout( t );
                        return false;
                    }
                    /* do the actual scroll */
                    window.scrollTo( 0, pos );

                    /* re-run the function until we reach the correct location */
                    t=setTimeout( arguments.callee, time );
                })();
            }


            function bindEvents(event){
                /*
                    Get a nodelist containing all the anchors of class "list-group-item"
                */
                var col=document.querySelectorAll('a.list-group-item');
                /*
                    Some browsers do not support using the forEach operator on a nodelist
                    so convert the nodelist ( which is array like ) into a true array
                    so that "forEach"  can be used.
                */
                Array.prototype.slice.call( col ).forEach(function(e,i,a){
                    /*
                        here
                        ----
                        "e" refers to the actual DOM node "a"
                        "i" refers to the "index" within the array
                        "a" is the array itself

                        Assign an "onclick" event listener making sure that
                        the "passive" flag is set to FALSE in this instance 
                        otherwise you will get an error 
                        "Unable to preventDefault inside passive event listener invocation."
                    */
                    e.addEventListener( 'click', scrollFaq, { passive:false, capture:false });
                });
            }


            /*
                Bind the events when the DOM is ready - here we can set the "passive" flag to true
            */
            document.addEventListener( 'DOMContentLoaded', bindEvents, { capture:false, passive:true } );
        </script>
        <style>
            .faqHeader{
                margin:0 0 100rem 0;
                border:1px solid black;
                display:block;
                height:100rem;
                font-size:1.5rem;
            }
            a.list-group-item{
                display:block;
                clear:none;
                margin:0 1rem 1rem 1rem;
                width:200px;
                padding:1rem;
                font-size:1rem;
                background:blue;
                color:white;
                border:1px solid black;
            }
        </style>
    </head>
    <body>
        <a name='top'></a>
    <?php
        $names=array(/* some random names */
            'marilyn','jane','rita','sue','bob','customer','worker'
        );
        foreach( $names as $name ){/* Note the use of the dataset attribute!!! */
            echo "<a class='list-group-item' href='#' data-name='$name'>$name</a>";
        }
        foreach( $names as $name ){
            echo "
            <div class='faqHeader' id='$name'>
                <a href='#top'>$name</a>
            </div>";
        }
    ?>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM