讓我們假設我有一些HTML這樣的:不能得到所選文本的容器(的jsfiddle可用)
<div id='fooBar' contenteditable='true'>Hello <span class="test">World</span></div>
JavaScript代碼:
var fooBar = document.getElementById('fooBar');
fooBar.addEventListener('click', function() {
console.log(window.getSelection().getRangeAt(0).commonAncestorContainer)
});
問:爲什麼不會它得到實際的容器命名測試?我不知道爲什麼這不會工作。我甚至用selection.anchorNode.parentElement試了一下。什麼都沒有現在,當查看從window.getSelection()獲得的對象的內部體系結構時,我看不到作爲屬性列出的span元素。我究竟做錯了什麼?
https://jsfiddle.net/w7bfmLqd/1/
這將幫助你:http://stackoverflow.com/questions/6897187/javascript- get-id-of-commonancestorcontainer – Mojtaba
他Range.commonAncestorContainer只讀屬性返回最深或最遠的文檔樹 - 包含範圍邊界點的節點。 – vaso123