How to make clickable anchor in contentEditable div?

前端 未结 4 489
Happy的楠姐
Happy的楠姐 2020-12-01 17:56

I have following code:

Blah blah Google Blah blah
4条回答
  •  一个人的身影
    2020-12-01 18:50

    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

提交回复
热议问题