<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>
最佳答案
当您更改选择值时似乎需要滚动到 anchor
第 1:更改选择器以选择并为其使用更改事件
第 2 步:使用 $(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>
Note: be sure to include jquery
关于javascript - 使用下拉菜单平滑滚动到 anchor 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34260184/