Problems with contenteditable span inside hyperlink in Firefox

浪尽此生 提交于 2020-06-17 05:15:52

问题


I've got a contenteditable span placed inside an <a> tag. I'd like to be able to edit the text inside the span so it is important to:

  • place the cursor on mouseclick somewhere inside the span
  • select part of the text inside the span using the mouse

Both does not work in Firefox as soon as there is a href attribute in the hyperlink (which is also needed in my case). There is no problem without this attribute and there are no problems in Chrome.

Please try my example on JSFiddle.

<ul>
  <li>
    <a href="#">
      <span contenteditable="true">PlacingCursorOrTextSelectionInFirefoxImpossible</span>
    </a>
  </li>
  <li>
    <a>
      <span contenteditable="true">noProblemsHereSoFar</span>
    </a>
  </li>
</ul>

回答1:


What you can do to improve the click behaviour is to prevent its propagation like this:

<a href="#">
  <span contenteditable="true" onclick="event.stopPropagation();">
    PlacingCursorOrTextSelectionInFirefoxImpossible
  </span>
</a>

Unfortunately, this only allows to put the cursor inside the span, but it is somewhy put to its beginning, not where one have clicked.

To enable selecting, you need to prevent the dragging behaviour, but it is to be changed for the a element:

<a href="#" draggable="false">
  <span contenteditable="true" onclick="event.stopPropagation();">
    PlacingCursorOrTextSelectionInFirefoxImpossible
  </span>
</a>

But wow, draggable="false" actually fixed the "cursor to beginning" bug! Here's the working example (tested in FF 47): https://jsfiddle.net/8v1ebkfd/4/




回答2:


This works for me:

  1. prevent click-default inside contenteditables
  2. and for firefox, remove and add href-attribute to prevent placing the cursor at the start of the contenteditable-element

http://jsfiddle.net/uy4q0zcm/1/

// if contenteditable inside a link
document.addEventListener('click', e=>{
    if (e.button !== 0) return;
    if (e.target.isContentEditable) {
        e.preventDefault();
    }
    if (e.explicitOriginalTarget && e.explicitOriginalTarget.isContentEditable) { // keyboard click firefox
        e.preventDefault();
    }
});

// prevent (Firefox) placing cursor incorrectly
document.addEventListener('mousedown', e=>{
    if (!e.target.isContentEditable) return;
    var link = e.target.closest('a');
    if (link) {
        const href = link.getAttribute('href')
        link.removeAttribute('href');
        setTimeout(()=>link.setAttribute('href', href))
    }
});


来源:https://stackoverflow.com/questions/37962939/problems-with-contenteditable-span-inside-hyperlink-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!