15

我有一个内容可编辑的 div,如下所示:

<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>

我使用以下代码:

<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>

当我在 div 中移动插入符号时单击该按钮,将返回 div 中插入符号的实际位置(偏移量)。

问题是当我用输入类型=文本或密码控件替换 contenteditable div,并保持 contenteditable 属性=true,然后单击按钮时,我总是得到零。为什么是这样?

感谢您的关注。

4

3 回答 3

17

在大多数浏览器中,window.getSelection()仅适用于文本节点内的选择和文档内的元素。它不适用于<input><textarea>元素中的文本(尽管在 WebKitwindow.getSelection().toString()中将返回焦点文本输入或文本区域中的选定文本。请参阅http://jsfiddle.net/PUdaS/)。要在输入中获取选择,请使用输入的selectionStartselectionEnd属性:

<input type="text" id="test" value="Some text">

<input type="button" value="Click me"
    onclick="alert(document.getElementById('test').selectionEnd);">

请注意,直到 8 版(包括版本 8)的 IE 不支持selectionStartandselectionEnd属性,因此需要一个不同的、更复杂的解决方案。IE 也不支持window.getSelection(),因此此代码将在您的原始代码支持的所有浏览器中运行。

于 2011-02-22T00:05:14.790 回答
1

这在很大程度上取决于您使用的浏览器,因为这是浏览器设计的一个怪癖,而不是 JavaScript。

在您的情况下发生的情况是,当您单击一个突出显示的<input type="button">同时,仍然突出显示。但是,当您单击或突出显示时,它们会失去焦点并删除突出显示(从而使您的代码失败)。<div><div><input type="button"><input type="text"><textarea>

我会仔细研究您要完成的工作,并考虑重新考虑您是如何解决这个问题的。

于 2011-02-21T23:05:53.603 回答
0

2 备注:

<input... >tag 不是一个标签,应该被关闭,<input ... />否则你应该使用这个<button>标签(但不是出于 X 浏览器合规性的原因)

如果您不想进入一个没有结束的故事,您可以重新考虑处理您的观点的方式如下:保持<div>原样并在其上触发一个 DOM 事件(而不是使用标签上的 onclick 事件) . 如果你会读法语,我在这里总结了很多例子。这种方式比你的第一种方式要重得多,但之后更强大,因为你可以在 DOM 上按你想要的方式触发事件,使用回调函数等等。

原理如下:
一方面是HTML页面

<div id="test"...>Lorem..</div>  
<script src="..."/>  

另一方面,非侵入式 javascript 代码

// your event handler here
function Dothisorthat(e) {
 // pop up the dom content or edit it or start an ajax request or whatever you need here
 return false;
}

// This is read in the third place  
function attacherAction() {
// Attach the action "Dothisorthat" on the event "onclick" occuring on your div "test"
id ='test'; // your div id
if (document.getElementById(id)) {
       zLink = document.getElementById(id);
       zLink.onclick = function() {
           Dothisorthat(this); // in your case, you can write a small function to pop up or edit the div content
       }
   }
}  
// This is read second
function addLoadEvent(func) {  
  var oldonload = window.onload;  
  if (typeof window.onload != 'function') {  
    window.onload = func;  
  } else {  
    window.onload = function() {  
      if (oldonload) {  
        oldonload();  
      }  
      func();
    }
  }
}  
    // This is read first
addLoadEvent(attacherAction);  

希望有帮助

于 2011-02-22T00:05:39.953 回答