Получите сфокусированный элемент изображения внутри contenteditable div - PullRequest
0 голосов
/ 27 мая 2018

Мне нужно изменить вставленное изображение внутри contenteditable div: изменить его пропорционально, добавить границы и т. Д. Возможно, этого можно достичь, добавив className, который изменит необходимые свойства CSS.Проблема в том, что я не знаю, как ссылаться на сфокусированное, т. Е. Активное, кликнутое изображение или любой другой элемент в этом отношении.

Это HTML-код, который я пытаюсь использовать

<!DOCTYPE html>
<html>

<body>

  <div contenteditable="true">This is a div. It is editable. Try to change this text.</div>

</body>

</html>

Ответы [ 2 ]

0 голосов
/ 27 мая 2018

Это то, что я пробовал, и похоже, что оно работает - по крайней мере, в моей системе созданный фрагмент не работает, к сожалению.

function getSelImg(){
var curObj;
window.document.execCommand('CreateLink',false, 'http://imageselectionhack/');
   allLinks =   window.document.getElementsByTagName('A');
   for(i = 0; i < allLinks.length; i++)
    {
      if (allLinks[i].href == 'http://imageselectionhack/')
       {
         curObj = allLinks[i].firstChild;
         window.document.execCommand('Undo'); // undo link
         break;
       }
    }
 
 if ((curObj) && (curObj.tagName=='IMG'))
 {
   //do what you want to...
	 curObj.style.border = "thick solid #0000FF";
 }
}	
<!DOCTYPE html>
<html>

<body>
<input type="button" onclick="getSelImg()" value="set img border">
<div contenteditable="true">This is a div.<br>
It is editable.<br>
Try to paste an image here:<br>
###########################<br>
<br>
<br>
<br>
###########################
</div>

</body>

</html>
0 голосов
/ 27 мая 2018

Использование css, html и javascript

Ваш редактируемый контент должен находиться внутри родительского div с идентификатором или именем класса, вы даже можете иметь разные div для изображений и тому подобное.

Тогда этоэто так же просто, как css:

#editableContentDiv img {
     imgProperty: value;
}

Тогда вы можете иметь javascript следующим образом:

function insertImage(){
    var $img = document.querySelector("#editableContentDiv img");
    $img.setAttribute('class','resize-drag');      
}

В конце концов, если у вас есть более одного img внутри одного div вы можете использовать querySelectorAll вместо querySelector, а затем перебирать теги img внутри того же div.

Я считаю, что это должно как минимум дать вам представление о том, с чего начатьхочу.

Подобный пример

Я обнаружил, что в этой сущности есть похожие вещи, которые вы хотите, но хотите немного сложнее.

function resizeMoveListener(event) {
  var target = event.target,
    x = (parseFloat(target.dataset.x) || 0),
    y = (parseFloat(target.dataset.y) || 0);

  // update the element's style
  target.style.width = event.rect.width + 'px';
  target.style.height = event.rect.height + 'px';

  // translate when resizing from top or left edges
  x += event.deltaRect.left;
  y += event.deltaRect.top;
  updateTranslate(target, x, y);
}

function dragMoveListener(event) {
  var target = event.target,
    // keep the dragged position in the data-x/data-y attributes
    x = (parseFloat(target.dataset.x) || 0) + event.dx,
    y = (parseFloat(target.dataset.y) || 0) + event.dy;
  updateTranslate(target, x, y);
}

function updateTranslate(target, x, y) {
  // translate the element
  target.style.webkitTransform =
    target.style.transform =
    'translate(' + x + 'px, ' + y + 'px)';

  // update the position attributes
  target.dataset.x = x;
  target.dataset.y = y;
}


function insertImage() {
  var $img = document.createElement('img');
  $img.setAttribute('src', 'https://vignette.wikia.nocookie.net/googology/images/f/f3/Test.jpeg/revision/latest?cb=20180121032443');
  $img.setAttribute('class', 'resize-drag');
  document.querySelector(".container-wrap").appendChild($img);

  var rect = document.querySelector(".container-wrap").getBoundingClientRect();
  $img.style.left = rect.left;
  $img.style.top = rect.top;
}

function dataTransfer() {

  //cleanup
  var $out = document.querySelector(".out-container-wrap");
  while ($out.hasChildNodes()) {
    $out.removeChild($out.lastChild);
  }

  //get source
  var source = document.querySelector('.container-wrap')

  //get data
  var data = getSource(source);

  //add data to target
  setSource($out, data);

}

/**
 * Get data from source div
 */
function getSource(source) {
  var images = source.querySelectorAll('img');
  var text = source.querySelector('div').textContent;

  //build the js object and return it.
  var data = {};
  data.text = text;

  data.image = [];

  for (var i = 0; i < images.length; i++) {
    var img = {}
    img.url = images[i].src
    img.x = images[i].dataset.x;
    img.y = images[i].dataset.y;
    img.h = images[i].height;
    img.w = images[i].width;

    data.image.push(img)
  }
  return data;
}

function setSource(target, data) {

  //set the images.
  for (var i = 0; i < data.image.length; i++) {

    var d = data.image[i];

    //build a new image
    var $img = document.createElement('img');
    $img.src = d.url;
    $img.setAttribute('class', 'resize-drag');
    $img.width = d.w;
    $img.height = d.h;
    $img.dataset.x = d.x;
    $img.dataset.y = d.y;


    var rect = target.getBoundingClientRect();
    $img.style.left = parseInt(rect.left);
    $img.style.top = parseInt(rect.top);
    //transform: translate(82px, 52px)
    $img.style.webkitTransform = $img.style.transform = 'translate(' + $img.dataset.x + 'px,' + $img.dataset.y + 'px)';
    //$img.style.setProperty('-webkit-transform', 'translate('+$img.dataset.x+'px,'+$img.dataset.y+'px)');
    target.appendChild($img);
  }

  //make a fresh div with text content
  var $outContent = document.createElement('div')
  $outContent.setAttribute('class', 'out-container-content');
  $outContent.setAttribute('contenteditable', 'true');
  $outContent.textContent = data.text;

  target.appendChild($outContent);
}

interact('.resize-drag')
  .draggable({
    onmove: dragMoveListener,
    inertia: true,
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: {
        top: 0,
        left: 0,
        bottom: 1,
        right: 1
      }
    }
  })
  .resizable({
    edges: {
      left: true,
      right: true,
      bottom: true,
      top: true
    },
    onmove: resizeMoveListener
  })
.resize-drag {
  z-index: 200;
  position: absolute;
  border: 2px dashed #ccc;
}

.out-container-content,
.container-content {
  background-color: #fafcaa;
  height: 340px;
}

#btnInsertImage {
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://code.interactjs.io/interact-1.2.4.min.js"></script>
</head>

<body>
  <button id="btnInsertImage" onclick="insertImage()">Insert Image</button>
  <div class="container-wrap">
    <div class="container-content" contenteditable="true">This is the content of the container. The content is provided along with the image. The image will be moved around and resized as required. The image can move within the boundary of the container.</div>
  </div>
  <button id="btnSubmit" onclick="dataTransfer()">Submit</button>
  <div class="out-container-wrap">
  </div>
</body>

</html>

Источник

...