1

Есть плагин для mce 3.5 который создает div с классом .incut. Плагин представляет из себя кнопку который генерирует блок, представленный в сниппете ниже. Нуобходимо после создания этого блока навесить на него два события: mouseenter и mouseleave. Сначала я прочел про live() и его сегодняшний аналог on. Сделал вот такое:

//функция вешает обработчики событий при наведении мыши и вызывает функцию
//создания элемента для удаления вырезки
function AddHoverButton() {
  const incut = document.querySelectorAll(".incut");
  [].forEach.call(incut, function(item) {
    item.addEventListener("mouseenter", function(event) {
      prependAndUncuteInsertEl(event.type, item);
    });
    item.addEventListener("mouseleave", function(event) {
      prependAndUncuteInsertEl(event.type, item);
    });
  });
}

//функция элемент для удаления врезки из текста
function prependAndUncuteInsertEl(type, element) {
  const iElement = document.createElement("i");
  iElement.className = "glyphicon glyphicon-remove";
  iElement.id = "deletingItem";
  if (type === "mouseenter") {
    element.prepend(iElement);
  } else if (type === "mouseleave") {
    const itemToDelete = document.getElementById("deletingItem");
    itemToDelete.remove();
    return false;
  }
  deleteInsertText(iElement, element);
}

//функция удаляет вставленный текст по нажатию на createdItem
function deleteInsertText(createdItem, elemToDelete) {
  createdItem.addEventListener("click", function(event) {
    elemToDelete.parentNode.removeChild(elemToDelete);
  });
}

$(document).on("mouseenter", ".incut", function(event) {
  prependAndUncuteInsertEl(event.type, this);
});

$(document).on("mouseleave", ".incut", function(event) {
  prependAndUncuteInsertEl(event.type, this);
});
.incut.left {
  border-right: 2px solid #c0c0c0;
  border-left: none;
  float: right;
  margin: 8px 20px 8px 0px;
}

.incut {
  width: 330px;
  position: relative;
}

.incut.left a {
  float: left;
}

.incut a {
  float: right;
  font-size: 14px;
  text-decoration: none;
  width: 314px;
}

.incut img {
  width: 314px;
  margin-bottom: 10px;
}

P {
  margin: 5px 0px 7px 0px;
}

#deletingItem {
  cursor: pointer;
  width: 100%;
  height: 100%;
}

#deletingItem::before {
  position: absolute;
  left: 20%;
  top: 0.5em;
  height: 100px;
  width: 160px;
  text-align: center;
  color: rgba(255, 246, 246, 1);
  font-size: 100px;
}
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="incut left">
  <a title="«Терранову» и «Шоколадницу» во Владивостоке закрыли по решению суда" href="https://primamedia.ru/news/693791/" data-mce-href="https://primamedia.ru/news/693791/"><img src="http://primamedia.ru/f/266x136/1507/1506378.jpg" alt="" data-mce-src="http://primamedia.ru/f/266x136/1507/1506378.jpg">«Терранову» и «Шоколадницу» во Владивостоке закрыли по решению суда</a>
</div>

Это работает, например, на codepen и тут, на SO (прыгает, правда). Но в случае, если DOM построен, а элемента на который нужно навесить обработчик еще нет, то данные события не срабатывают и крестик не появляется. Я решил сделать через DOMMutations. Код получился вот таким:

window.onload = function() {
  //функция вешает обработчики событий при наведении мыши и вызывает функцию
  //создания элемента для удаления вырезки
  function AddHoverButton() {
    const incut = document.querySelectorAll(".incut");
    [].forEach.call(incut, function(item) {
      item.addEventListener("mouseenter", function(event) {
        prependAndUncuteInsertEl(event.type, item);
      });
      item.addEventListener("mouseleave", function(event) {
        prependAndUncuteInsertEl(event.type, item);
      });
    });
  }

  //функция элемент для удаления врезки из текста
  function prependAndUncuteInsertEl(type, element) {
    const iElement = document.createElement("i");
    iElement.className = "glyphicon glyphicon-remove";
    iElement.id = "deletingItem";
    if (type === "mouseenter") {
      element.prepend(iElement);
    } else if (type === "mouseleave") {
      const itemToDelete = document.getElementById("deletingItem");
      itemToDelete.remove();
      return false;
    }
    deleteInsertText(iElement, element);
  }

  //функция удаляет вставленный текст по нажатию на createdItem
  function deleteInsertText(createdItem, elemToDelete) {
    createdItem.addEventListener("click", function(event) {
      elemToDelete.parentNode.removeChild(elemToDelete);
    });
  }

  // Select the node that will be observed for mutations
  var targetNode = document.querySelector(
    ".mceIframeContainer.mceFirst.mceLast"
  );
  console.log(targetNode instanceof Node);
  // Options for the observer (which mutations to observe)
  var config = {
    attributes: true,
    childList: true
  };

  // Callback function to execute when mutations are observed
  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == "childList") {
        $(document).on("mouseenter", ".incut", function(event) {
          prependAndUncuteInsertEl(event.type, this);
        });

        $(document).on("mouseleave", ".incut", function(event) {
          prependAndUncuteInsertEl(event.type, this);
        });
      } else if (mutation.type == "attributes") {
        $(document).on("mouseenter", ".incut", function(event) {
          prependAndUncuteInsertEl(event.type, this);
        });

        $(document).on("mouseleave", ".incut", function(event) {
          prependAndUncuteInsertEl(event.type, this);
        });
      }
    }
  };

  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(callback);

  // Start observing the target node for configured mutations
  observer.observe(targetNode, config);
};
.incut.left {
  border-right: 2px solid #c0c0c0;
  border-left: none;
  float: right;
  margin: 8px 20px 8px 0px;
}

.incut {
  width: 330px;
  position: relative;
}

.incut.left a {
  float: left;
}

.incut a {
  float: right;
  font-size: 14px;
  text-decoration: none;
  width: 314px;
}

.incut img {
  width: 314px;
  margin-bottom: 10px;
}

P {
  margin: 5px 0px 7px 0px;
}

#deletingItem {
  cursor: pointer;
  width: 100%;
  height: 100%;
}

#deletingItem::before {
  position: absolute;
  left: 20%;
  top: 0.5em;
  height: 100px;
  width: 160px;
  text-align: center;
  color: rgba(255, 246, 246, 1);
  font-size: 100px;
}
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="mceIframeContainer mceFirst mceLast">
  <div class="incut left">
    <a title="«Терранову» и «Шоколадницу» во Владивостоке закрыли по решению суда" href="https://primamedia.ru/news/693791/" data-mce-href="https://primamedia.ru/news/693791/"><img src="http://primamedia.ru/f/266x136/1507/1506378.jpg" alt="" data-mce-src="http://primamedia.ru/f/266x136/1507/1506378.jpg">«Терранову» и «Шоколадницу» во Владивостоке закрыли по решению суда</a>
  </div>
</div>

Тут я использовал window.onload, поскольку в переменную targetNode не попадает узел и возвращался null, т.к файл в котором лежит данный файл загружался быстрее плагина tinymc. Теперь я получаю в консоль на моменте console.log(targetNode instanceof Node); true, и поставленный мною breakpoint говорит, что до observer.observe(targetNode, config); дело доходит, но вот почему то все равно при добавлении элемента на него не навешиваются обработчики событий и ничего не работает.

Как можно исправить данный код, чтобы он работал так, как работает первый сниппет (с уже созданным элементом)?

UPD: возможно, вам станет интересна структура DOM дерева, вот она:

введите сюда описание изображения

4
  • вы хотите на странице навесить обработчик на элемент внутри iframe что ли?
    – teran
    17 мая 2018 в 8:06
  • ну да, а почему нет? он же доступен через document.querySelector 17 мая 2018 в 8:08
  • возьмите ваш первый кусок кода, и создайте на его основе минимальный пример для воспроизведения проблемы.
    – teran
    17 мая 2018 в 9:25
  • @teran реализовал пример) второй сниппет 17 мая 2018 в 10:16

1 ответ 1

0

Придется ответить на свой собственный вопрос. В общем, с чем пришлось столкнуться: iframe загружался сильно позже основной страницы, из за этого не работало даже событие DOMContentLoaded, срабатывало только window.onload. В общем, сделал вот так:

window.onload = function() {
  $(document.getElementById("cont_ifr").contentWindow.document).ready(function(
    e
  ) {
    //переопределяю документ, чтобы можно было работать в локальном контексте iframe 
    var document = this.getElementById("cont_ifr").contentWindow.document;
    var cssLink = document.createElement("link");
    cssLink.href =
      //а тут я вставляю в iframe bootstrap ибо верстка для меня недосягаема
      "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";
    cssLink.rel = "stylesheet";
    cssLink.type = "text/css";
    this.getElementById("cont_ifr").contentWindow.document.body.appendChild(
      cssLink
    );

    //функция элемент для удаления врезки из текста
    function prependAndUncuteInsertEl(type, element) {
      const iElement = document.createElement("i");
      iElement.className = "glyphicon glyphicon-remove";
      iElement.id = "deletingItem";
      if (type === "mouseenter") {
        element.prepend(iElement);
      } else if (type === "mouseleave") {
        const itemToDelete = document.getElementById("deletingItem");
        itemToDelete.remove();
        return false;
      }
      deleteInsertText(iElement, element);
    }

    //функция удаляет вставленный текст по нажатию на createdItem
    function deleteInsertText(createdItem, elemToDelete) {
      createdItem.addEventListener("click", function(event) {
        elemToDelete.parentNode.removeChild(elemToDelete);
      });
    }

    $(document).on("mouseenter", ".incut", function(event) {
      prependAndUncuteInsertEl(event.type, this);
    });

    $(document).on("mouseleave", ".incut", function(event) {
      prependAndUncuteInsertEl(event.type, this);
    });
  });
};

Обратите внимание, что в this у нас теперь главный document всей страницы, а в document - локальный, который принадлежит нашему iframe. Как выглядит верстка представлено в вопросе, в самом низу.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.