添加滚动到 Div 函数并使用 UI 自动完成

Adding Scroll to Div Function With UI Auto Complete

能否请您看一下 This Demo 并告诉我如何启用从自动完成滚动到所选项目的 div?

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
        $('html,body').animate({
               scrollTop: $("#"+ this.value).offset().top
         });
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

但我收到此错误

Uncaught TypeError: Cannot read property 'top' of undefined

change 事件不存在,因此您的代码未被触发。你必须这样做:

$(document).ready(function () {
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
        $('html,body').animate({
               scrollTop: $("#"+ this.value).offset().top
         });
    });
});

检查this demo

代码在正确触发时有效。但只有当您输入与其中一个查找项的 ID 匹配的值时,它才会正确触发。

根据 ID 选择器的 Jquery documentation

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient.

并且根据 MDN document.getElementById 参数

  • element 是对 Element 对象的引用,如果具有指定 ID 的元素不在文档中,则为 null。
  • id 是一个区分大小写的 字符串,表示正在查找的元素的唯一 ID。

由于您的元素是使用 Proper Cased 字符串使用 id 定义的,并且由于 id 查找区分大小写,如果您为 Asp 元素输入 asp,它将 return null 用于查找。

随后在 null 上调用 offset() 将 return undefined。由于 undefined 没有 属性 top,您会收到错误消息:

Uncaught TypeError: Cannot read property 'top' of undefined

因此解决方案是将您的 ID 设置为某种大小写并规范化您的调用。例如,如果您使用小写字母,则:

$("#"+ this.value.toLower()).offset().top

或者更好的是做一些空检查等,以确保在开始调用方法之前您确实拥有一个项目:

function getOffset(id){
   if (this.value)
   {
      var matches = $("#"+ this.value.toLower());
      if (matches.length){
         return matches.offset().top;
      }
   }
   return 0;
}

scrollTop: getOffset(this.value);