Стили не применяются в цветных блоках а курсор редактирования отсутсвует
Перенесла цветные блоки на визуальный редактор чтобы посмотреть как будет работать. В итоге при добавления цветных блоков, стили не применяются, а курсор редактирования почему-то отсутствует, хотя в предыдущем примере все работало https://javascript.ru/forum/misc/839...redaktora.html.
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script> <style> /*стили заметок*/ .shortcodestyle { font: 14px arial; line-height: 1.4; padding: 15px 15px 15px 75px; word-wrap: break-word; border-radius: 2px; clear: both; margin: 10px auto; max-width: 660px; position: relative; text-decoration: none; } /*Внимание*/ .warning { background: #fff2b8 url("images/warning.png") no-repeat scroll 15px 50%; border-bottom: 2px solid #EAD18C; color: #4F2012; } .warning a { color: #D15225; } /*Информация*/ .info { background: #bae5f8 url("images/info.png") no-repeat scroll 15px 50%; border-bottom: 2px solid #9BBFC4; color: #0F2B33; } .info a { color: #216CAF; } /*Важно*/ .important { background: #ffcaca url("images/important.png") no-repeat scroll 15px 50%; border-bottom: 2px solid #f4a9a9; color: #330D0D; } .important a { color: #ff3a37; } /*Совет*/ .advice { background: #ccfacc url("images/advice.png") no-repeat scroll 15px 50%; border-bottom: 2px solid #b1dbb1; color: #0b280b; } .advice a { color: #5E9800; } /*Нейтральность*/ .neutrality { background: #f5f5f5 url("images/neutrality.png") no-repeat scroll 15px 50%; border-bottom: 2px solid #dfdfdf; color: #222; } .neutrality a { color: #5587c4; } </style> </head> <body> <input type='button' class='btn-block' data-command='Bold' value='B'/><input type='button' class='btn-block' data-command='Italic' value='I'/> <button type="button" class="btn-block" data-command="warning" title="Внимание">Внимание</button> <button type="button" class="btn-block" data-command="important" title="Важно">Важно</button> <button type="button" class="btn-block" data-command="info" title="Информация">Информация</button> <button type="button" class="btn-block" data-command="advice" title="Совет">Совет</button> <button type="button" class="btn-block" data-command="neutrality" title="Нейтральность">Нейтральность</button> <br /> <iframe scrolling='no' frameborder='no' src='#' id='frameId' name='frameId'></iframe> <form name="myform" action="#" method="post" onsubmit="return save()"> <p> <input type="hidden" id="content" name="content" value="" /> </p> <script type="text/javascript"> let edit1; let doc; function init() { var isGecko = navigator.userAgent.toLowerCase().indexOf("gecko") != -1; console.log(isGecko); var iframe = document.getElementById("frameId"); edit1 = iframe.contentWindow; doc = iframe.contentDocument; iHTML = "<html><head></head><body></body></html>"; doc.open(); doc.write(iHTML); doc.close(); doc.designMode = "on"; doc.body.contentEditable = true; $('.btn-block').on("click", function(e) { e.preventDefault(); e.stopPropagation(); let target = e.target; tag = target.firstChild; let myclass = ""; if (target.getAttribute("data-command") === "Bold") { edit1.focus(); edit1.document.execCommand("bold", null, ""); } if (target.getAttribute("data-command") === "Italic") { edit1.focus(); edit1.document.execCommand("italic", null, ""); } if (target.getAttribute("data-command") === "warning") { myclass = "warning shortcodestyle"; addBlock(myclass); } else if (target.getAttribute("data-command") === "important") { myclass = "important shortcodestyle"; addBlock(myclass); } else if (target.getAttribute("data-command") === "info") { myclass = "info shortcodestyle"; addBlock(myclass); } if (target.getAttribute("data-command") === "advice") { myclass = "advice shortcodestyle"; addBlock(myclass); } if (target.getAttribute("data-command") === "neutrality") { myclass = "neutrality shortcodestyle"; addBlock(myclass); } }); function addBlock(myclass) { var rangeElement = document.createElement("div"); rangeElement.setAttribute("class", myclass); rangeElement.innerHTML = "<p><br></p>"; doc.body.append(rangeElement); var range = document.createRange(); range.setStart(rangeElement.childNodes[0], 0); range.collapse(true); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); rangeElement.focus(); } } init(); //}); </script> <p> <input type="submit" value="Отправить" /> </p> <div class="warning shortcodestyle">Внимание:</div> </form> </body> |
Разобралась сама, для начала стили нужно перенести в отдельный файл и добавить в body, тот который создается во время запуска скрипта, пример:
iHTML = "<html><head>"; iHTML += "<link rel=\"stylesheet\" type=\"text/css\" href=\"style2.css\">"; iHTML += "</head><body></body></html>"; Теперь с курсором. Он не фокусируется на нужном контейнере потому, что с первого раза не удалось получить нужный dom-узел. Поэтому также переделаем код. var range = edit1.document.createRange(); range.setStart(rangeElement.childNodes[0], 0); range.collapse(true); edit1.focus(); var sel = edit1.document.getSelection(); sel.removeAllRanges(); sel.addRange(range); rangeElement.focus(); Итоговый результат: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script> </head> <body> <input type='button' class='btn-block' data-command='Bold' value='B'/><input type='button' class='btn-block' data-command='Italic' value='I'/> <button type="button" class="btn-block" data-command="warning" title="Внимание">Внимание</button> <button type="button" class="btn-block" data-command="important" title="Важно">Важно</button> <button type="button" class="btn-block" data-command="info" title="Информация">Информация</button> <button type="button" class="btn-block" data-command="advice" title="Совет">Совет</button> <button type="button" class="btn-block" data-command="neutrality" title="Нейтральность">Нейтральность</button> <br /> <iframe scrolling='no' frameborder='no' src='#' id='frameId' name='frameId'></iframe> <form name="myform" action="#" method="post" onsubmit="return save()"> <p> <input type="hidden" id="content" name="content" value="" /> </p> <script type="text/javascript"> let edit1; let doc; function init() { var isGecko = navigator.userAgent.toLowerCase().indexOf("gecko") != -1; console.log(isGecko); var iframe = document.getElementById("frameId"); edit1 = iframe.contentWindow; doc = iframe.contentDocument; iHTML = "<html><head>"; iHTML += "<link rel=\"stylesheet\" type=\"text/css\" href=\"style2.css\">"; iHTML += "</head><body></body></html>"; doc.open(); doc.write(iHTML); doc.close(); doc.designMode = "on"; doc.body.contentEditable = true; $('.btn-block').on("click", function(e) { e.preventDefault(); e.stopPropagation(); let target = e.target; tag = target.firstChild; let myclass = ""; if (target.getAttribute("data-command") === "Bold") { edit1.focus(); edit1.document.execCommand("bold", null, ""); } if (target.getAttribute("data-command") === "Italic") { edit1.focus(); edit1.document.execCommand("italic", null, ""); } if (target.getAttribute("data-command") === "warning") { myclass = "warning shortcodestyle"; addBlock(myclass); } else if (target.getAttribute("data-command") === "important") { myclass = "important shortcodestyle"; addBlock(myclass); } else if (target.getAttribute("data-command") === "info") { myclass = "info shortcodestyle"; addBlock(myclass); } if (target.getAttribute("data-command") === "advice") { myclass = "advice shortcodestyle"; addBlock(myclass); } if (target.getAttribute("data-command") === "neutrality") { myclass = "neutrality shortcodestyle"; addBlock(myclass); } }); function addBlock(myclass) { var rangeElement = document.createElement("div"); rangeElement.setAttribute("class", myclass); rangeElement.innerHTML = "<p><br></p>"; doc.body.append(rangeElement); var range = edit1.document.createRange(); range.setStart(rangeElement.childNodes[0], 0); range.collapse(true); edit1.focus(); var sel = edit1.document.getSelection(); sel.removeAllRanges(); sel.addRange(range); rangeElement.focus(); } } init(); //}); </script> <p> <input type="submit" value="Отправить" /> </p> </form> </body> P.S. При запуске скрипта стили по прежнему не видны, потому что они находятся в отдельном документе. |
Katy93,
если что-то в коде повторяется, значит это можно сделать один раз или вынести в отдельную функцию. можно addBlock(myclass); убрать везде а в строку 79 добавить. |
рони, я тоже подумала единожды вызвать функцию addBlock, но только у меня там еще есть теги "B" и "I" и когда я выношу addBlock(myclass); за скобки, то теги "B" и "I" перестают работать.
|
Часовой пояс GMT +3, время: 22:59. |