两个相同的函数工作方式不同

Two same function working differently

本文关键字:函数 工作 方式不 两个      更新时间:2023-09-26

我试图在一个可满足的div内插入图像。它在chrome, firefox, opera和safari中工作。但不能在ie浏览器中工作。我看到了这个帖子,它说insertImage在IE中工作。但我不知道为什么它不能在这里工作。

看到这个jsfiddle,它在jsfiddle网站上运行得很好。

html:

<input type="button" onmousedown="insertImage(); return false" value="insert image" unselectable="on">
<div contenteditable="true">Click somewhere in here and press the button</div>

js

function insertImage() {
    var sel = document.selection;
    if (sel) {
        var textRange = sel.createRange();
        document.execCommand('insertImage', false, "http://jsfiddle.net/img/logo.png");
        textRange.collapse(false);
        textRange.select();
    } else {
        document.execCommand('insertImage', false, "http://jsfiddle.net/img/logo.png");
    }
}

但是当我用我的函数执行相同的函数时,它不能正常工作。只有当我突出显示或选择一些文本时,它才会起作用。我如何通过在我的js脚本中获得元素id来实现相同的结果?请帮帮我。谢谢你。

html:

<button id="btn-insert_image">image</button>
<div id="content" contenteditable="true">
  <p>How does it work? Just put your image size after our URL and you'll get a placeholder.</p>
</div>

js:

$(document).ready(function() {
  $('#btn-insert_image').click(function() {
    document.execCommand('insertImage', false, 'http://placehold.it/350x150');
  });
});

jsfiddle

unselectable="on"添加到图像按钮中,如下所示

<button id="btn-insert_image" unselectable="on">image</button>

这应该使它在IE中工作。

看起来像在IE中,当你点击图像按钮时,你失去了选择。

<<p> 用来控制属性/strong>

注意
将UNSELECTABLE属性设置为off并不能确保元素是可选择的。一个例子是将SELECTION属性设置为no的HTML应用程序(HTA)。HTA主体中的元素不能被选中,即使元素的UNSELECTABLE属性被设置为off。

当你点击一个UNSELECTABLE属性设置为on的元素时,任何现有的当前选择都不会被破坏。

将UNSELECTABLE属性设置为on的元素可以包含在从元素外部开始的选择中。UNSELECTABLE属性是作为展开来实现的。将文档对象的expando属性设置为false将排除所有expando的功能。

$(document).ready(function () {
  $('#btn-italic').click(function () {
    document.execCommand('italic');
  });
  $('#btn-bold').click(function () {
    document.execCommand('bold');
  });
  $('#btn-insert_image').click(function () {
    var sel = document.selection;
    if (sel) {
      var textRange = sel.createRange();
      document.execCommand('insertImage', false, "http://lorempixel.com/100/50/abstract");
      textRange.collapse(false);
      textRange.select();
    } else {
      document.execCommand('insertImage', false, "http://lorempixel.com/100/50/abstract");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn-insert_image" unselectable="on">image</button>
<button id="btn-italic"><i>i</i>
</button>
<button id="btn-bold"><b>B</b>
</button>
<div id="content" contenteditable="true">
  <p>How does it work? Just put your image size after our URL and you'll get a placeholder.</p>
</div>