如何在contentEditable div中编辑链接

问题描述 投票:10回答:3

有人对如何在contentEditable div中编辑链接有任何建议吗?一旦用鼠标单击该链接或光标单击该链接,将弹出一个小提示并允许用户更改该链接的href属性,这将是理想的选择。提示不是问题,但是如何检测到该链接已被单击或光标已到达该链接?在Firefox和Safari上的contentEditable div中,onfocus似乎不起作用。有什么想法吗?

javascript html contenteditable
3个回答
16
投票

我很确定这就是您要寻找的东西,但是我使用jQuery只是为了使该概念更易于模拟。 jsbin预览可用,所以快看吧。如果有人为了答案可以将其转换为纯JS,我已将其设为社区Wiki。

它通过绑定到可编辑div上的keyup / click事件,然后使用window.getSelection()(对于标准)或document.selection(对于那些IE人员)来检查用户插入符号所在的节点。其余代码处理弹出/处理编辑。

jQuery方法:

function getSelectionStartNode(){
  var node,selection;
  if (window.getSelection) { // FF3.6, Safari4, Chrome5 (DOM Standards)
    selection = getSelection();
    node = selection.anchorNode;
  }
  if (!node && document.selection) { // IE
    selection = document.selection
    var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
    node = range.commonAncestorContainer ? range.commonAncestorContainer :
           range.parentElement ? range.parentElement() : range.item(0);
  }
  if (node) {
    return (node.nodeName == "#text" ? node.parentNode : node);
  }
}

$(function() {
    $("#editLink").hide();
    $("#myEditable").bind('keyup click', function(e) {
        var $node = $(getSelectionStartNode());
        if ($node.is('a')) {
          $("#editLink").css({
            top: $node.offset().top - $('#editLink').height() - 5,
            left: $node.offset().left
          }).show().data('node', $node);
          $("#linktext").val($node.text());
          $("#linkhref").val($node.attr('href'));
          $("#linkpreview").attr('href', $node.attr('href'));
        } else {
          $("#editLink").hide();
        }
    });
    $("#linktext").bind('keyup change', function() {
      var $node = $("#editLink").data('node');
      $node.text($(this).val());
    });
    $("#linkhref").bind('keyup change', function() {
      var $node = $("#editLink").data('node');
      $node.attr('href', $(this).val());
      $node.and('#linkpreview').attr('href',$(this).val());
    });
});

0
投票

我只在铬上测试过

按钮样式

button.cmd {
 ...
}

工具栏按钮

<button type="button" id="linkEditor" class="cmd">link</button>

模式对话框->链接编辑器

<div id="optionDialog" class="modal">
    <div class="modal-content">
        <div id="linkOption">
            <p>
                <label>Indirizzo link</label><br />
                <input type="text" id="linkUrl" value="" placeholder="http://www..." />
            </p>
            <p>
                <label>Testo link</label><br />
                <input type="text" id="linkData" value="" placeholder="link label" />
            </p>
            <p>
                <button type="button" id="linkDone">apply</button>
                <button type="button" id="cancel">cancel</button>
            </p>
        </div>
    </div>
</div>

javascript,jQuery

var cur_range;
var cur_dialog;

$(document).ready(function() {
    $('.editor').focus();

    //on toolbar button mousedown keep current range
    $('.cmd').mousedown(function(event) {
        event.preventDefault();
        try {
            cur_range = document.getSelection().getRangeAt(0);
        }
        catch(error) {
            console.log(error);
        }
    });

    $('#linkEditor').click(function() {
        event.preventDefault();

        //if user select edit link, else insert link
        if (!cur_range.collapsed) {
            //if selection is a link set edit values
            if (cur_range.commonAncestorContainer.parentNode.nodeName.toLowerCase() == 'a') {
                $('#linkUrl').val(cur_range.commonAncestorContainer.parentNode.href);
                $('#linkData').val(cur_range.commonAncestorContainer.data);
            }
            else {
                //alert here
                return false;
            }
        }
        else {
            $('#linkUrl').val('');
            $('#linkData').val('');
        }
        //open link editor dialog
        $('#optionDialog').show();
        $('#linkOption').show();

        //store current dialog section (link, table, header)
        cur_dialog = $('#linkOption');
    });

    $('#linkDone').click(function() {
        event.preventDefault();
        if (cur_range.collapsed) {
            //insert link at caret position
            var node = '<a href="' + $('#linkUrl').val() + '" target="_blank">' + $('#linkData').val() + '</a>';
            cur_range.insertNode(cur_range.createContextualFragment(node));
        }
        else {
            //replace existing link values
            cur_node = cur_range.commonAncestorContainer.parentNode;
            cur_node.href = $('#linkUrl').val();
            cur_node.innerText = $('#linkData').val();
        }
        //update range
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(cur_range);
        document.getSelection().collapseToEnd();
        $('.modal-close').click();

        //if you don't use observer some code is nedeed
        //save_history(1);
    });

    //When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        optionDialog = document.getElementById('optionDialog');
        if (event.target == optionDialog) {
            $('#optionDialog').hide();
            cur_dialog.hide();
            cur_dialog = null;
        }
    }
});

0
投票

我发现了更多的解决方案。它使用内置函数而不是jQuery。https://developer.mozilla.org/ru/docs/Web/Guide/HTML/Editable_content

© www.soinside.com 2019 - 2024. All rights reserved.