我有以下html结构:
<div id="grandparent">
<div id="parent">
<p>
high light me with mouse!! highlight me with mouse!!highlight me with mouse!!
</p>
</div>
</div>我有这个js代码:
$(document).mouseup(function (event) {
var target=event.target;
target=$(target);
var parent = target.parent();
console.log(parent.parent().attr("id"));
if (window.getSelection) {
var selection = window.getSelection();
selectedText = selection.toString();
console.log(selectedText);
}
});因此,这段代码只是控制台记录选定的文本。
但是我有一个问题-当我不是单击我的<p>元素而只是单击文档时-然后我移动鼠标来选择按住左键的文本,我无法获得父div的id,因为
var target=event.target;目标成为文档元素
发布于 2017-04-06 21:32:08
将$(document).mouseup(更改为$("#parent").mouseup(。
代码:
$("#parent").mouseup(function (event) {
var target=event.target;
target=$(target);
var parent = target.parent();
console.log(parent.parent().attr("id"));
if (window.getSelection) {
var selection = window.getSelection();
selectedText = selection.toString();
console.log(selectedText);
}
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grandparent">
<div id="parent">
<p>
high light me with mouse!! highlight me with mouse!!highlight me with mouse!!
</p>
</div>
</div>
https://stackoverflow.com/questions/43256108
复制相似问题