How can I make an HTML multiple select act like the control button is held down always

前端 未结 4 1579
慢半拍i
慢半拍i 2020-12-17 15:47

I have a web application I\'m working on that requires a HTML multiple select element operates like the control key is held down at all times. I.e. click on an option will

4条回答
  •  太阳男子
    2020-12-17 16:17

    Had to solve this problem myself and noticed the bugged behavior a simple interception of the mousedown and setting the attribute would have, so made a override of the select element and it works good.

    jsFiddle: http://jsfiddle.net/51p7ocLw/

    Note: This code does fix buggy behavior by replacing the select element in the DOM. This is a bit agressive and will break event handlers you might have attached to the element.

    window.onmousedown = function (e) {
        var el = e.target;
        if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
            e.preventDefault();
    
            // toggle selection
            if (el.hasAttribute('selected')) el.removeAttribute('selected');
            else el.setAttribute('selected', '');
    
            // hack to correct buggy behavior
            var select = el.parentNode.cloneNode(true);
            el.parentNode.parentNode.replaceChild(select, el.parentNode);
        }
    }

    From

提交回复
热议问题