我有一个内容可编辑的 div,其跨度如下:
<div contenteditable="true">some <span>spanned</span> text</div>
我想知道是否有任何事件监听器可以附加到span
元素本身可用于检测插入符是否在元素内部移动span
元素。
我并不是在寻找有听众的答案div
,每次有活动时运行检查div
,比如这个答案的解决方案:
当插入符进入特定 div/span/a 标签以及插入符离开标签时触发事件 https://stackoverflow.com/questions/27004757/firing-an-event-when-the-caret-gets-within-a-particular-div-span-a-tag-and-also
你可以使用变异观察者 https://developer.mozilla.org/de/docs/Web/API/MutationObserver。并检查characterData
观察者回调中的变化。
这是一个例子:
var MutationObserver =
window.MutationObserver ||
window.WebKitMutationObserver ||
window.MozMutationObserver;
var config = { childList: true, characterData: true, characterDataOldValue:true, subtree: true };
var target = document
.querySelector('div[contenteditable]')
.getElementsByTagName('span')
.item(0);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'characterData') {
console.clear();
console.log('old value:', mutation.oldValue);
console.log('new value:', mutation.target.textContent);
}
});
});
observer.observe(target, config);
<div contenteditable="true">some <span>spanned</span> text</div>
检查插入符是否刚刚进入span
一个简单的click
听众应该做这项工作。
var target = document
.querySelector('div[contenteditable]')
.getElementsByTagName('span')
.item(0)
.addEventListener('click', function(evt) {
console.log('caret entered:', evt.target)
})
<div contenteditable="true">some <span>spanned</span> text</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)