平滑滚动与下拉菜单链接到锚点标签

3
<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>
1个回答

1

看起来你需要在更改选择器值时滚动到锚点,因此

第一步:将选择器更改为select,并使用change事件

第二步:使用$(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>

演示

注意: 确保包含jQuery库。


它不起作用。我已经在Firefox和Chrome上尝试过了。 - Jubiki
@JudiaValenciaKrakowski 我更新了我的答案,并提供了演示。如果你不需要在加载时滚动,请从代码末尾删除.change()。 - Mohamed-Yousef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接