Javascript: prevent mouse cursor from moving the cursor (prevent it from changing)

I have a situation where I click on the button, I need the current selection before clicking. Sample code looks like

$('div#test').on('click', 'span', function () {
    sel = window.getSelection();
    $('div#out p').text(sel.toString());
});

The expected behavior is shown here - http://jsfiddle.net/yvondtm/NH2DW/

Everything happens correctly when the image button is pressed. If you make a selection before clicking on the image, you will get the result - here it is just a copy of your choice.

But if you click on the text button, the selection will be lost and the result will not be as expected. Clicking on the text seems to move the cursor and therefore change the selection.

I checked the CSS-solutions such as this to turn off the selection, as I put in the violin -webkit-user-select: none;. He does what he says, but does no help — although range selection is not allowed, the carriage is still moving!

How can I solve this problem? Should I find a way to convert the text button as if it were an image?

(No problem using js or jquery or css to achieve this.)

+4
source share
3 answers

, mousedown, click, - window.getSelection() . , <span>, #sp

#sp {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

: http://jsfiddle.net/NH2DW/3/


, , . JavaScript, .

$('div#di').on('click', 'span', function () {
    $('div#out p').text(selection);
});

var selection = '', onSelect = function(_event) {
    if($(_event.target).is(':not(div#di span)'))
        selection = window.getSelection().toString();
    else return false;
};
$(document).mouseup(onSelect).keyup(onSelect).mousedown(onSelect);

: http://jsfiddle.net/NH2DW/7/

+3
$('div#di').on('click', 'span', function (e) {
    $('div#out p').html($(e.currentTarget).html());
});
0

. , , , .

<div id="container">
    <span id="wrapper">
        <img src="transparent image" id="overlay_img" />
        <p id="button_text"> Or you can use transparent property </p>
    </span>
</div>

CSS 'img#overlay_img'

position: absolute;
width: 100%; /* strech image to cover entire span */
height: 100%;
top: -1px; /* minor adjustments if the span has padding */
left: -1px;

- CSS

js

$('div#container').on('click', 'span', function () {
    sel = window.getSelection();
    $('div#out p').text(sel.toString());
});

Working fiddle (overlay image looks ugly but works) - http://jsfiddle.net/yvondtm/NH2DW/8/

0
source

Source: https://habr.com/ru/post/1548739/


All Articles