How to make clickable anchor in contentEditable di

2019-01-11 22:54发布

问题:

I have following code:

<div contentEditable="true">
    Blah blah <a href="http://google.com">Google</a> Blah blah
</div>

Fiddle

Is there a way to make this a clickable, not editable, without moving anchor outside that div?

回答1:

Just wrap the link in another div, like so:

<div contentEditable="true">

    <div contentEditable="false">
            Bla bla <a href="http://google.com">Google</a> Bla bla
    </div>
</div>​


回答2:

Make the link itself uneditable (works at least on HTML5):

<a contenteditable="false" href="http....... >



回答3:

As far as I am aware, there is no way of doing this without programming it yourself using Javascript. The simple way to do this is to disable and reenable contentEditable whenever the Ctrl key is pressed. So when Ctrl is pressed, the link is clickable, otherwise not. This means you can still edit the content of the link. This functionality is similar to that of Microsoft Word, IIRC.

The code might look something like this:

var content = document.getElementById('content');

document.addEventListener('keydown', function(event) {
    if (event.keyCode === 17) {          // when ctrl is pressed
        content.contentEditable = false; // disable contentEditable
    }
}, false);

document.addEventListener('keyup', function(event) {
    if (event.keyCode === 17) {          // when ctrl is released
        content.contentEditable = true;  // reenable contentEditable
    }
}, false);

Updated fiddle



回答4:

To get a clickable and editable link, I put an onclick-command in the link. Example:

<a contenteditable="true" href="necessary?" onclick="document.location = 'www.xy.com';" ...>
    <img src="image.jpg" draggable="true" ...>
</a>

Disadvantages have been: In IE the link had to be clicked twice. In mobile Safari the keyboard was shown (Could be hidden with Javascript).