【问题标题】:Smooth Scrolling with Dropdown Menu to Anchor Tags使用下拉菜单平滑滚动以锚定标签
【发布时间】:2015-12-14 05:12:48
【问题描述】:
<select>
<option value="#anchor">Anchor</option>
</select>

<a id="anchor">Anchor</a>

我试图让它平滑滚动,但到目前为止还没有奏效。我在网上找到的可行教程是常规的垂直菜单,而不是下拉菜单。有谁知道如何让这个工作?我一直在用这个:

<script>
$(document).ready(function(){
    $('option[value^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 1000, 'swing', function () {
            window.location.hash = target;
        });
    });
});
</script>

【问题讨论】:

    标签: javascript jquery html css dropdown


    【解决方案1】:

    当您更改选择值时,您似乎需要滚动到锚点

    第一个:改变你的选择器来选择和使用它的改变事件

    第二个:使用$(this).val();获取选择值

    <script>
    $(document).ready(function(){
        $('select').on('change',function (e) {
            e.preventDefault(); // no need to use this line
            var target = $(this).val();
            var $target = $(target);
    
            $('html, body').animate({
                'scrollTop': $target.offset().top
            }, 1000, 'swing', function () {  // swing here will work if you include jquery-ui  without that it will not make a effect
                //window.location.hash = target;
            });
        }).change();
    });
    </script>
    

    Working Demo

    注意:一定要包含jquery

    【讨论】:

    • 它不起作用。 Firefox 和 chrome 都试过了。
    • @JudiaValenciaKrakowski 如果加载时不需要滚动,我会用演示更新我的答案,只需从最后的代码中删除 .change()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多