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