javascript - li 元素溢出时在 div 上自动滚动

标签 javascript jquery html css

<分区>

我正在尝试在 div 中应用自动滚动。我现在有一个固定高度 div 下的元素列表,当我在第 3 个突出显示 li 元素(即 Compt0005)div 自动滚动后按下键时。任何人都可以解决它..

演示:- here

最佳答案

此代码通过 .getBoundingClientRect() 设置 div 的 scrollTop 属性方法:

$(function () {
    var liPossition = 0;
    var items = $("#ulSearch li");
    var divSearchContent = $("#divSearchContent");
    divSearchContent.hide();
    $("#txtSearch").keydown(function (e) {
        if (e.keyCode == 13) { // if enter pressed
            $("#txtSearch").val(items.eq(liPossition).text());
            divSearchContent.hide();
            return;
        }
        if (e.keyCode != 38 && e.keyCode != 40) { // // if not up or down arrow
            return;
        }
        divSearchContent.show();
        items.eq(liPossition).css("background-color", "");
        if (e.keyCode == 40 && liPossition < items.length - 1) { // down arrow key code
            liPossition++;
        }
        if (e.keyCode == 38 && liPossition > 0) { // up arrow key code
            liPossition--;
        }
        items.eq(liPossition).css("background-color", "red");//[0].scrollIntoView(); return;
        var b1 = divSearchContent[0].getBoundingClientRect();
        var b2 = items.eq(liPossition)[0].getBoundingClientRect();
        if (b1.top>b2.top) {
            divSearchContent.scrollTop( divSearchContent.scrollTop()-b1.top+b2.top );
        }
        else if (b1.bottom<b2.bottom) {
            divSearchContent.scrollTop( divSearchContent.scrollTop()-b1.bottom+b2.bottom );
        }
    });
});

JSFiddle

关于javascript - li 元素溢出时在 div 上自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18359270/

相关文章:

javascript - 无法在js中将数据推送到空数组中

javascript - 超链接回发后保持滚动位置

html - 中心 DIV 和响应式

javascript - 后退在 HTML 中不起作用

Wordpress 中的 HTML 表格,造成无意识的差距

javascript - 滚动时淡入和淡出的图像(jquery)

javascript - 如何在 D3 中访问 JSON 时添加授权 header

javascript从纪元字符串转换为日期对象

javascript - jQuery 查找表行但忽略子表中的行

javascript - 查看 html 表单是否已更改