javascript如何在标签中包装iframe文本?

时间:2017-08-23 16:07:55

标签: javascript html css

我有一个iframe,用户可以输入文字并按下按钮。当按下按钮时,我希望突出显示的文本包含在div标签中,如下所示:

<div id="quote">text here</div>

我该怎么做?我确实希望div具有&#34;引用&#34;的ID。到目前为止,这是我的代码:

 <center><iframe name="richTextField" id="richTextField" ><?php echo $text;</iframe></center>
 <a class="buttonOnBar" id="btn14_quote" type="button" value="" onClick="javascript:iquote();" title="Quoteify"><img id="btnOnBarImg"src="img/icons/quote.png"></a>

1 个答案:

答案 0 :(得分:0)

在这里,我在浏览器中对此进行了测试。抱歉,我无法使用代码段,但他们的iframe不允许访问其他iframed页面(即使他们是“null-domain”页面)。但要确保样式标记在您的标题中,否则它将无法正常工作(然后您不会看到我丑陋的默认样式;-)

<iframe srcdoc='Lorem ipsum dolor sit amet, consecteteur adipscing elit' id='rtf'></iframe>
<button id='make-div'>Make div</button>
<style>
.foo {
    background: red;
    color: white;
}
</style>
<script>
    onload = function() {
        var rtf = document.getElementById('rtf');
        rtf.contentDocument.designMode = 'on';
        document.getElementById('make-div').onclick = function() {
            var html = rtf.contentWindow.getSelection();
            var success = rtf.contentDocument.execCommand('insertHTML', false, '<span class="foo">'+html+'</span>');
            if (!success) { alert('Functionality not supported by browser.'); }
        };
    }
</script>

此答案中使用的主要功能的来源:https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand