Показать сообщение отдельно
  #1 (permalink)  
Старый 28.04.2022, 18:22
Кандидат Javascript-наук
Отправить личное сообщение для Katy93 Посмотреть профиль Найти все сообщения от Katy93
 
Регистрация: 28.12.2018
Сообщений: 138

Как картинку окружить ссылкой при использовании функции Image?
Делаю добавление картинок, при нажатии на кнопку, добавляется только одна картинка, потом сделаю форму загрузку. Сейчас конкретно меня интересует как окружить тег img ссылкой и добавить уже картинку ссылку при условии что я использую функцию Image.

К примеру пользователь просматривает контент и видит картинки средних размеров, чтобы рассмотреть детали он нажимает на ссылку-картинку и открывает картинку в соседнем окне браузера.

Как это сделать?

Вот тестовая функция добавления картинки.
function insertImg()
      {
          var img=new Image();
   
          img.onload=function()
          {
            
            j = $('iframe, body').contents().find("span.marker");
            
            j.replaceWith(img);
          }
          img.src="https://322327.selcdn.ru/pleerru/5aecfcf45dd80fb56ca2fd14825b1a9c.jpg";
      }

А вот код полностью:
<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="image" title="Картинка">Картинка</button>
<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' width="800" height="400"></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 += "<style>";
      iHTML += ".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;}";
      iHTML += ".warning {background: #fff2b8 url(\"images/warning.png\") no-repeat scroll 15px 50%; border-bottom: 2px solid #EAD18C; color: #4F2012;}";
      iHTML += ".warning a {color: #D15225;}";
      iHTML += ".info {background: #bae5f8 url(\"images/info.png\") no-repeat scroll 15px 50%;border-bottom: 2px solid #9BBFC4;color: #0F2B33;}";
      iHTML += ".info a {color: #216CAF;}";
      iHTML += ".important {background: #ffcaca url(\"images/important.png\") no-repeat scroll 15px 50%;border-bottom: 2px solid #f4a9a9;color: #330D0D;}";
      iHTML += ".important a {color: #ff3a37;}";
      iHTML += " .advice {background: #ccfacc url(\"images/advice.png\") no-repeat scroll 15px 50%;border-bottom: 2px solid #b1dbb1;color: #0b280b;}";
      iHTML += ".advice a {color: #5E9800;}";
      
      iHTML += ".neutrality {background: #f5f5f5 url(\"images/neutrality.png\") no-repeat scroll 15px 50%;border-bottom: 2px solid #dfdfdf;color: #222;}";
      iHTML += ".neutrality a {color: #5587c4;}";
      iHTML += "body > p {border: 1px dashed #000;}";
      
      iHTML += "</style>";
      iHTML += "</head><body><span class=\"marker\" style=\"display: none; line-height: 0;\"></span></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") === "image") {
           // alert(target.getAttribute("data-command"));
            insertImg();
          }
          
          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 insertImg()
        {
            var img=new Image();
     
            img.onload=function()
            {
              
              j = $('iframe, body').contents().find("span.marker");
              
              j.replaceWith(img);
            }
            img.src="https://i.ytimg.com/vi/ORxm0hkVuo8/hqdefault.jpg";
        }
       
       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>
Ответить с цитированием