Limit total entries displayed by datalist

后端 未结 2 1433
予麋鹿
予麋鹿 2020-12-05 14:46

When there is a long set of elements in a datalist, they will all get displayed with a scroll bar next to them. Is there an easy way to only display the top 5, and just cut

2条回答
  •  忘掉有多难
    2020-12-05 15:15

    With some modern javascript and html you could do something like this.

    Here's the document:

    
    
    
    

    And here's the js:

    var search = document.querySelector('#search');
    var results = document.querySelector('#searchresults');
    var templateContent = document.querySelector('#resultstemplate').content;
    search.addEventListener('keyup', function handler(event) {
        while (results.children.length) results.removeChild(results.firstChild);
        var inputVal = new RegExp(search.value.trim(), 'i');
        var clonedOptions = templateContent.cloneNode(true);
        var set = Array.prototype.reduce.call(clonedOptions.children, function searchFilter(frag, el) {
            if (inputVal.test(el.textContent) && frag.children.length < 5) frag.appendChild(el);
            return frag;
        }, document.createDocumentFragment());
        results.appendChild(set);
    });
    

    And here's a live example: http://jsfiddle.net/gildean/yxafa/6/

提交回复
热议问题