Make text “more” selectable

前端 未结 6 1952
心在旅途
心在旅途 2021-02-01 17:48

I have text in a

tag:

Hello world... and goodbye mind A B!

How do I increase the area in which the te

6条回答
  •  既然无缘
    2021-02-01 18:42

    From my test it works on the iphone as well as ff and chrome - if someone can test on android I'll appreciate feedback!

    The border obviously can be removed.

    This code uses code from this answer (part of the SelectText() function): Selecting text in an element (akin to highlighting with your mouse)

    Fiddle

    Code:

    function extendSelection() {
        var extendBy = arguments.length <= 0 || arguments[0] === undefined ? 15 : arguments[0];
    
        var extended = document.getElementsByClassName('extendedSelection');
        [].slice.call(extended).forEach(function (v) {
            var bounds = v.getBoundingClientRect();
            var x = bounds.left;
            var r = textWidth(v.innerHTML, ''+ css(v, 'font-weight') +' ' + css(v, 'font-size') + ' ' + css(v, 'font-family') );
            var y = bounds.top;
            var w = bounds.width;
            var h = bounds.height;
            var element = document.createElement('div');
            element.style.position = 'absolute';
            element.style.height = h + extendBy + 'px';
            element.style.width = r + extendBy + 'px';
            element.style.left = x - extendBy / 2 + 'px';
            element.style.top = y - extendBy / 2 + 'px';
            element.style.border = '1px dotted black';
            document.body.appendChild(element);
            element.addEventListener('click', function (e) {
                SelectText(v);
            });
            element.addEventListener('touchend', function (e) {
                SelectText(v);
            });
        });
    }
    
    function css(element, property) {
        return window.getComputedStyle(element, null).getPropertyValue(property);
    }
    
    function textWidth(text, font) {
        var el = textWidth.canvas || (textWidth.canvas = document.createElement("canvas"));
        var draw = el.getContext("2d");
        draw.font = font;
        var m = draw.measureText(text);
        return m.width;
    };
    
    function SelectText(element) {
        var doc = document,
            text = element,
            range,
            selection;
        if (doc.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
            selection.setSelectionRange(0, element.value.length)
        }
    }
    
    extendSelection();
    

提交回复
热议问题