I am using a html editor to edit content. Now i need to make sure a very special kind of element does not get deleted (images with a special class).

For the use cases of a non-collapsed selection/range with BACKSPACE, DELETE, CTRL + X/CMD + X i found a solution, but i am still looking for a solution to the case that the selection/range is not collapsed and the next Backspace will delete one of my special images.

How can i detect if the next Backspace/Delete will remove one of those img-tags ?

Example: CARET marks the caret/cursor position. If Backspace will be pushed next the image will get removed. How can i detect this case?

<p>Some Text <b>here <img class="my class" src="..."/></b>CARET some text</p>
有帮助吗?

解决方案

The code below detects elements around caret with onkeyup (and onselectionchange), but it's for IE only. Maybe it can be "translated" to jQuery.

function detectClass(){
    var range, parentR, parentL;
    range = document.selection.createRange();
    range.moveStart('character',1);
    range.moveEnd('character',1);
    parentR = range.parentElement();
    range.moveStart('character',-2);
    range.moveEnd('character',-2);
    parentL = range.parentElement();
    if (parentR.className == 'special'){/* special on right */}
    if (parentL.className == 'special'){/* special on left */}
    return;
}

其他提示

For the case of checking whether the caret is next to an image, here's an answer of mine to a similar question. It relies on Rangy for IE < 9 support but can be trivially made to not rely on Rangy.

The answer only considers backspace but could easily be adapted to work for Delete as well.

https://stackoverflow.com/a/10020476/96100

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top