当选择发生变化时,停止多个选择从滚动到顶部

时间:2016-04-12 13:11:51

标签: javascript jquery html

我有一个多选列表,用于过滤网格。当我选择或取消选择列表中的任何项目时,它会触发一个事件。

问题在于,当我向下滚动并选择或取消选择列表中较低的值时,它会跳回到顶部。我怎么能阻止这种情况发生?

我做了一个小提琴:https://jsfiddle.net/Berge90/a2two97o/

修改:Chrome中的问题。在Edge和Firefox中正常工作

HTML

<div class="FilterContainer">
    <select id="SelectTenant" multiple="true">
    </select><br/>
    <button onclick="setAllTenantSelections(true)">Select All</button>
    <button onclick="setAllTenantSelections(false)">Select None</button>
</div>

的Javascript

window.onload = setupFilter;
window.onload = populateTenantFilter;
gridHeaders = [{name: "Test"},{name: "Value"},{name: "Another one"},{name: "And another"},{name: "Last one"}];

//Selecting/Deselecting all values
function setAllTenantSelections(selected) {
    var select = document.getElementById("SelectTenant");
    for (element in select.children) {
        select[element].selected = selected;
        showCol(select[element].text, selected);
    }
}

//Adding all values from array to list
function populateTenantFilter() {
    var select = document.getElementById("SelectTenant");
    select.innerHTML = "";
    for (i = 0; i < gridHeaders.length; i++) {
        var option = document.createElement("Option");
        option.innerHTML = gridHeaders[i].name;
        select.appendChild(option);
    }
    //setting all options as selected on load
    setAllTenantSelections(true);
    setupFilter();
}

//Adding onclick-events to the values
function setupFilter() {
    $('select option').on('mousedown', function (e) {
        this.selected = !this.selected;
        if (this.selected) {
            console.log("SELECTED: " + this.text);
            showCol(this.text,true);
        } else {
            console.log("DESELECTED: " + this.text);
            showCol(this.text,false);
        }
        e.preventDefault();
    });
}

function showCol(){
        //Filtering grid based on selection
}

1 个答案:

答案 0 :(得分:4)

我通过在下一个事件循环中滚动回到原始scrollTop来解决了这个问题:

$('.your-selector').mousedown(e => {
    var el = e.target;
    e.preventDefault();

    // ...your code

    // fixes erratic scroll behaviour in Chrome
    var scrollTop = el.parentNode.scrollTop;
    setTimeout(() => el.parentNode.scrollTo(0, scrollTop), 0);
});