문제

HTML 편집기를 만들고 있습니다. 아래의 출력으로 지금 입력하고있는이 편집기와 비슷합니다. 나는 iframe을 사용하고 $ htmltextbox.val ()을 iframe의 본문에 버리고 있습니다.

나는 Iframe 내부에서 스타일 시트를 만들려고 노력하고있어 작동하는만큼 좋아 보입니다.

미리 감사드립니다!

$htmlTextBox.keyup(function(){
    SetPreview();
});   

function SetPreview()
{
    var doc = $preview[0].contentWindow.document;
    var $body = $("body", doc);

    $body.html($htmlTextBox.val());
}
도움이 되었습니까?

해결책

당신이있는 동안 ~할 수 있다 iframe의 문서와 상호 작용하십시오 .Stylesheets, 구식 신뢰할 수있는 방법은 처음에 스타일 시트를 두는 것입니다 (iframe-src를 작성하여 원하는 스타일 시트가있는 빈 문서를 가리키면). document.write(). 예를 들어:

<body>
    <iframe></iframe>
    <script type="text/javascript">

        var d= frames[0].document;
        d.open();
        d.write(
            '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional //EN" "http://www.w3.org/TR/html4/loose.dtd">'+
            '<html><head><style type="text/css">'+
            'body { font-size: 200%; }'+
            '<\/style><\/head><body><\/body><\/html>'
        );
        d.close();

        d.body.innerHTML= '<em>Hello</em>';
    </script>
</body>

(이것은 또한 당신이 원하는 것이라고 가정 할 때 iframe 문서를 표준 모드로 설정합니다.)

다른 팁

후속 조치 :

HTML

<iframe id="message" name="message" />

jQuery

setTimeout(function() {
    var $head = $("#message").contents().find("head");                
    $head.append($("<link/>", 
        { rel: "stylesheet", href: url, type: "text/css" }
    ));                
}, 1); 

스타일 태그를 iframe에 삽입 할 수 있습니다.

<style type="text/css" id="cssID">
.className
{
    background-color: red;
}
</style>

<iframe id="iFrameID"></iframe>

<script type="text/javascript">
    $(function () {
        $("#iFrameID").contents().find("head")[0].appendChild(cssID);
        //Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
    });
</script>

이 코드를 JHTMLAREA 소스에서 아래로 가져 왔습니다. 재미있는 것은, 기능이 거기에 있었고 나는 그것을 몰랐다는 것입니다. 나는 이것을 구현하는 방법을 알아 내려고했을 때이 질문을 발견했다. :)

이것은 실제로 "jQuery"는 아니지만 작동합니다. 나는 Append와 함께 무언가를 징계하고 있습니다. iframe과 함께 작동하지 않아서 구식 학교를했습니다. Bobince의 대답도 좋아 보이고 더 신뢰할 수 있습니까? 지금까지 이것은 잘 작동하는 것 같습니다.

var e = edit.createElement('link'); 
e.rel = 'stylesheet'; 
e.type = 'text/css'; 
e.href = options.css; 
this.iframe[0].contentWindow.document.getElementsByTagName('head')[0].appendChild(e);

편집하다: 이것이 효과가있는 이유는 그것이 Samedomain (JS에서 iframe을 포함한 포함)이라면 일반적인 브라우저 보안 블록으로 인해 iframe dom을 조작하는 것을 방지 할 수 있습니다.

보다 Iframe에 CSS를 적용하는 방법

당신이 동일한 도메인에 있고 크로스 도메인 보안을 다루지 않는다고 가정하면, iframe이 iframe뿐만 아니라 내부의 문서가로드되었는지 확인하고 싶을 것입니다! (이것은 사용하려고 노력하는 동안 잠시 동안 나를 매달았다 .load())

그런 다음 jQuery를 사용하여 내용에 액세스하고 헤드에 액세스하고 스타일 시트를 머리에 추가하십시오.

 $(document.getElementById('yourIframeID').contentWindow.document).ready(function() {
      $('yourIframeID').contents().find('head').append('<link rel="stylesheet" href="/path/to/stylesheet/style.css" type="text/css" />');
 });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top