如何知道所选文本是否在特定 div 内
我有两个 div,如下所示:
<div id="div1">
<p>something</p>
<div><table><tr><td>Div1</td></tr></table></div>
</div>
<div id="div2">
<p>something else</p>
<div><table><tr><td>Div2</td></tr></table></div>
</div>
<button type="button">Check</button>
现在,我想知道何时选择某些文本然后按下按钮,所选文本是否位于“div1”下。我怎样才能做到这一点?
编辑:该解决方案必须在 IE-7 及更高版本中工作。
I have two divs as shown below:
<div id="div1">
<p>something</p>
<div><table><tr><td>Div1</td></tr></table></div>
</div>
<div id="div2">
<p>something else</p>
<div><table><tr><td>Div2</td></tr></table></div>
</div>
<button type="button">Check</button>
Now, I want to know when some text is selected and then the button pressed, if the selected text is under "div1" or not. How can I do that?
Edit: And the solution has to work in IE-7 and above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
2022 答案
下面的
elementContainsSelection()
函数返回一个布尔值,表示指定元素是否包含用户的全部选择并适用于所有现代浏览器。2011 答案
下面的
elementContainsSelection()
函数返回一个布尔值,表示指定元素是否包含用户的整个选择,并且适用于所有主要浏览器,包括 IE 6。现场演示:http://jsfiddle.net/eT8NQ/
代码:
2022 answer
The
elementContainsSelection()
function below returns a boolean representing whether the specified element contains the whole of the user's selection and works in all modern browsers.2011 answer
The
elementContainsSelection()
function below returns a boolean representing whether the specified element contains the whole of the user's selection and works in all major browsers, including IE 6.Live demo: http://jsfiddle.net/eT8NQ/
Code:
您可以观察每个 div 上的 mouseup 事件,并将以下方法绑定到它:
然后此方法将返回选定的文本,它会告诉您选择过程在触发该事件的 div 上结束。如果您需要起点,则必须将 mousedown 事件绑定到 div,这会将元素 id 存储在变量中,以便您可以确定选择过程的起点和终点,并找出中间有哪些 div。
如果 getSelected 方法返回空字符串,则应重置起点和终点。
you could observe a mouseup event on each div, and bind the following method to it:
this method will then return the selected text, it will tell you that the selection process ended on the div that fired the event. if you need the startpoint to, you have to bind a mousedown event to the divs, that will store the elements id in a variable, so you can determine the start- and endpoint of the selection process and find out which divs lie in between.
if the getSelected-method returns an empty string, you should reset start- and endpoint.
像这样的东西:
something like: