const test = document.querySelector('#test');
const html = test.innerHTML;
const words = html.split(/ /);
let newHtml = '';
for (var i = 0; i < words.length; i++) {
newHtml += '<span>' + words[i] + '</span> ';
}
test.innerHTML = newHtml;
test.querySelectorAll('span').forEach(el => {
el.addEventListener('click', (e) => {
if (e.target.parentElement.nodeName !== 'DDS') {
const wrapper = document.createElement('dds');
// insert wrapper before el in the DOM tree
e.target.parentNode.insertBefore(wrapper, e.target);
// move el into wrapper
wrapper.appendChild(e.target);
}
});
});
dds{
color:red;
}
<p id="test">This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>
1条答案
按热度按时间z18hc3ub1#
最简单的方法是为每个单词使用
span
,并通过将其 Package 在所需的标记中来为其给予一个click事件