0
我實現了富文本編輯器與創建鏈接功能。我可以創建鏈接,但是當我想更新鏈接時,例如,我點擊一個現有的錨節點並點擊「鏈接」按鈕,它不顯示原始網址。我怎樣才能讓它顯示原始的網址?到目前爲止,這是我所:如何從getSelection()獲取錨href jQuery的
$.fn.createRichTextEditor = function(width, height = "auto") {
var iframeDocument;
var iframeDocumentId = this.attr("id") + "-rte-editor";
var newHtml = "<div id='rte-" + iframeDocumentId + "' class='rte'>" +
"<ul class='rte-toolbar'>" +
"<li id='createLink'><button id='rte-createLinkBtn-" + iframeDocumentId + "' class='rte-button-link' value='createLink' title='Link'>Create Link</button></li>" +
"</ul>" +
'<div id="' + iframeDocumentId + '-container"></div>' +
"</div>";
this.after(newHtml);
this.css('display', 'none');
var iframe = $('<iframe/>', {
id: iframeDocumentId,
class: 'rte-iframe',
style: 'width;100%;height:' + height,
load: function() {
iframeDocument = this.contentDocument;
iframeDocument.designMode = 'On';
$(this).find('body').html('<br><br/>');
this.contentWindow.focus(); //New
}
});
$('#' + iframeDocumentId + '-container').append(iframe);
};
$('.rte-button-link').click(function() {
var sText = iframeDocument.getSelection();
var anchorTag = sText.anchorNode.parentNode;
var url = $(anchorTag).prop('href');
if (!url) {
url = "https://";
}
var input = prompt("Please enter a url", url);
if (input !== null) {
iframeDocument.execCommand('insertHTML', false, '<a href="' + input + '" onclick="window.open(\'' + input + '\')" style="cursor: pointer;">' + sText + '</a>');
}
});
$("#editor").createRichTextEditor(500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="editor">
</div>
嗨謝謝,它的工作原理!另一個問題是,當我使用getSelection()時,它也抓取額外的空間,我不能得到實際的錨標記。任何想法如何解決這個問題? – coffeeak
你到底得到了什麼? – Rohit416
未定義...... – coffeeak