【问题标题】:Permitting moving only of <img>s within contentEditable <div>只允许在 contentEditable <div> 中移动 <img>
【发布时间】:2011-01-25 15:13:50
【问题描述】:

我正在努力使用标记为contentEditablediv 来实现我想要的行为。我希望允许用户在div 内移动img 并使其保持内联,但不要让他们调整大小或以其他方式修改img。否则他们应该能够修改 div 中的文本。

默认浏览器行为如下所示,img 可以通过拖动手柄移动和调整大小:

<html>
  <head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
  </head>
  <body>

    <div id="edit" contenteditable="true">
      Here is some text, and also an <img src="http://img841.imageshack.us/img841/1747/imagead.png" /> image
    </div>

  </body>
</html>

我一直在尝试各种客户端脚本以尝试实现所需的功能,但我尝试的每种组合似乎都遇到了困难。我可以通过以下方式实现终极锁定:

<script type="text/javascript">
  $(document).ready(function() {
    $('img', '#edit').each(function (i, item) {
      item.contentEditable = false;
      $(item).bind('mousedown', function (e) {
        e.preventDefault();
      });
      if ($.browser.msie) {
        item.oncontrolselect = function () { return false; }
      }
    });
  });
</script>

但是虽然这可以防止任何元素重复(我在 Firefox 中遇到的问题)和使用拖动句柄(在 IE 中)调整大小,但根本无法移动 img

更新:感谢你们,到目前为止我得到的最接近的是:

<script type="text/javascript">
  $(document).ready(function() {
    $('img', '#edit').each(function (i, item) {
      attachEvents(item);
    });

    if ($.browser.mozilla) {
      document.execCommand("enableObjectResizing", false, false);
    }
  });

  function attachEvents(item) {
    if ($.browser.msie) {
      item.attachEvent('onresizestart', function (e) { 
        e.returnValue = false; 
      }, false);
      item.attachEvent('ondragend', function (e) { 
        // cannot get IE to rebind moved item (toElement or similar is not available until IE9 when using addEventListener)
        attachEvents(e.srcElement);
      }, false);
    } 
    if ($.browser.opera) {
      // doesn't seem to work at all in Opera 11
    }
  }
</script>

但剩下的两个问题是 Opera 完全缺乏支持(我可以忍受的东西)以及如何在 IE 中重新绑定事件 ondragend 的问题。

其他人可以帮忙吗?

【问题讨论】:

  • 您可能希望将这种东西标记为“javascript”以及 jQuery。

标签: javascript jquery html dom contenteditable


【解决方案1】:

您可以在img 上使用JQuery ui 实现可拖动效果。

【讨论】:

    【解决方案2】:

    在某些浏览器(尤其是 Firefox,但不是 IE)中,您可以使用 document.execCommand()enableObjectResizing 命令禁用调整大小句柄:

    document.execCommand("enableObjectResizing", null, false);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多