简体   繁体   中英

Smooth scrolling using javascript on anchor link

I want to make smooth scrolling using javascript in php program 在此处输入图片说明 As shown in image if i clicked on the customer from my left side bar then i want to smooth scrolling using javascript onclick function what i do?here i pass dynamic id whic are i fetched from my database

<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>

Try This :

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

Make sure you give this Id to your div in for loop like this

<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>

A simple example of how you could achieve the smooth scrolling to an element without using 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>

Or, a better approach that doesn't involve inline event handlers and now uses your original classNames.

The Javascript function does not need to be declared inside whatever loop you have - indeed to do so would be incorrect. Declare the functions at the top of the page and invoke accordingly as shown here. You could copy either example, save and run to see the scroll effect -then it is trivial to adapt to your "use-case"

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM