这是我目前的代码:https://jsfiddle.net/e8en0htn/
的Javascript
var addition = document.createElement('div');
addition.innerHTML = 'TEST CONTENT HERE';
addition.className = 'test-content';
var highlighted = document.querySelector('.highlight');
highlighted.parentNode.parentNode.insertBefore(addition,highlighted.parentNode);
目前代码只是在.test-content
的父元素之前插入.highlight
。我尝试做的是在.test-content
的父母之前或之后插入.highlight
一些元素。
这里棘手的部分:它可以是之前/之后的3个元素,之前/之后的5个元素等等。因为它将取决于.highlight
的数据属性:data-position
应该决定是否出现在元素之前或之后; data-howfar
应该决定它会出现多远(先前3个元素,2个元素等)。
我对previousSibling
和nextSibling
提出了一些有趣的想法,但显然有太多.previousSibling.previousSibling.previousSibling这样非常方便(特别是当数据属性为{{1时)太多data-howfar="20"
s)。
不幸的是,我坚持使用那个解决方案......任何想法?
答案 0 :(得分:0)
我认为这应该接近你的需求(你可以调整它):
var addition = document.createElement('div');
addition.innerHTML = 'TEST CONTENT HERE';
addition.className = 'test-content';
var highlighted = document.querySelector('.highlight');
var pos = highlighted.getAttribute('data-position');
var where = highlighted.getAttribute('data-howfar');
//highlighted.parentNode.parentNode.insertBefore(addition,highlighted.parentNode);
var container= highlighted.parentNode.parentNode;
var child = container.children;
for(i=0;i<child.length;i++) {
if(pos=='before') {
if(child[i]==highlighted.parentNode) {
selected=child[i-parseInt(where)];
selected.style.color='red';
container.insertBefore(addition,selected);
}
}
if(pos=='after') {
if(child[i]==highlighted.parentNode) {
selected=child[i+parseInt(where)];
//selected.style.color='red';
container.insertBefore(addition,selected);
}
}
}
strong { font-family:sans-serif; color:#f00000; }
.test-content { background: #f00000; color:#fff; padding:5px; }
<div class="content">
<p>
Lorem ipsum dolor sit amet, mel eu soluta adolescens, eu vel viris iudicabit definiebas, latine detracto lucilius id vis. Simul vituperata neglegentur qui ea, ex pri cibo alienum deleniti. Omnes omnesque democritum eam ea, est ut modo iriure laoreet. Possit luptatum scriptorem sed et, cu vitae audire corpora mea. Ea mea elitr tritani voluptaria, nostrud delectus ut cum. Ea per imperdiet splendide, duo ex mutat adhuc harum.
</p>
<p>
Usu suscipit necessitatibus no, sea at mazim ancillae scripserit. Nec ex facer petentium reprimique, qui ex tempor copiosae. Eum assum sensibus no. At sed vide paulo nostro, at modo postea officiis his, sale mundi aperiri at vel.
</p>
<p>
At vim civibus offendit, dolore persequeris vis ut. In eos dicant dissentiunt, cu causae epicurei est, natum veritus mnesarchum vim ex. An nam oportere adolescens. Ei diam modus iriure sed.
</p>
<p>
Cum liber dolorum fabellas id, vim dicta legimus in, natum perpetua signiferumque cum ea. In nibh viderer duo. Consul essent est ex, meis autem utinam eam ut. Quo ei errem quaestio temporibus.
</p>
<p>
Perfecto legendos pro no, vim ut imperdiet pertinacia. Te pri verear alterum, at atqui nostrud contentiones qui. Mel accumsan adolescens cu, quot singulis sea at, ex ius feugiat forensibus. Eu putent sanctus pro. No zril deserunt philosophia eum, id eum animal albucius electram, eum everti gubergren ne.
</p>
<p>
Lorem ipsum dolor sit amet, mel eu soluta adolescens, eu vel viris iudicabit definiebas, latine detracto lucilius id vis. Simul vituperata neglegentur qui ea, ex pri cibo alienum deleniti. Omnes omnesque democritum eam ea, est ut modo iriure laoreet. Possit luptatum scriptorem sed et, <strong class="highlight" data-position="before" data-howfar="3">cu vitae audire corpora mea. Ea mea elitr tritani voluptaria,</strong> nostrud delectus ut cum. Ea per imperdiet splendide, duo ex mutat adhuc harum.
</p>
<p>
Usu suscipit necessitatibus no, sea at mazim ancillae scripserit. Nec ex facer petentium reprimique, qui ex tempor copiosae. Eum assum sensibus no. At sed vide paulo nostro, at modo postea officiis his, sale mundi aperiri at vel.
</p>
<p>
At vim civibus offendit, dolore persequeris vis ut. In eos dicant dissentiunt, cu causae epicurei est, natum veritus mnesarchum vim ex. An nam oportere adolescens. Ei diam modus iriure sed.
</p>
<p>
Cum liber dolorum fabellas id, vim dicta legimus in, natum perpetua signiferumque cum ea. In nibh viderer duo. Consul essent est ex, meis autem utinam eam ut. Quo ei errem quaestio temporibus.
</p>
<p>
Perfecto legendos pro no, vim ut imperdiet pertinacia. Te pri verear alterum, at atqui nostrud contentiones qui. Mel accumsan adolescens cu, quot singulis sea at, ex ius feugiat forensibus. Eu putent sanctus pro. No zril deserunt philosophia eum, id eum animal albucius electram, eum everti gubergren ne.
</p>
</div>
所以,使用children
,并循环遍历节点...为了测试目的,所选的孩子被涂成红色......
编辑:如果你想要多个元素/插入,你可以使用这样的东西:
var highlighted = document.querySelectorAll('.highlight');
adds=[];
for(c=0;c<highlighted.length;c++) {
var addition = document.createElement('div');
addition.innerHTML = 'TEST CONTENT HERE';
addition.className = 'test-content';
adds.push(addition);
}
console.log(adds);
//highlighted.parentNode.parentNode.insertBefore(addition,highlighted.parentNode);
var container = document.getElementsByClassName('content')[0];
var child = container.children;
for (i = 0; i < child.length; i++) {
for (j = 0; j < highlighted.length; j++) {
pos = highlighted[j].getAttribute('data-position');
where = highlighted[j].getAttribute('data-howfar');
if (child[i] == highlighted[j].parentNode) {
if (pos == 'before') {
selected = child[i - parseInt(where)];
selected.style.color = 'red';
container.insertBefore(adds[j], selected);
}
if (pos == 'after') {
selected = child[i + parseInt(where)];
selected.style.color = 'red';
container.insertBefore(adds[j], selected);
}
}
}
}
DEMO:https://jsfiddle.net/e8en0htn/4/
P.S。你(可能)必须测试/设置一些限制,但它不应该太难。 ;)
答案 1 :(得分:0)
您可以使用这样的函数来获取元素需要插入的位置。
我试图跳过逻辑中的文本节点,但您可以根据自己的要求进行调整。
var getPosition = function(distance, direction, node)
{
var i = 0;
var newNode = null;
if(direction == "prev"){
while (i < distance)
{
newNode = node.previousSibling;
node = newNode;
if(newNode.nodeType != 3)
i++
}
}
else
{
while (i < distance)
{
newNode = node.nextSibling;
node = newNode;
if(newNode.nodeType != 3)
i++
}
}
return node;
}
var addition = document.createElement('div');
addition.innerHTML = 'TEST CONTENT HERE';
addition.className = 'test-content';
var highlighted = document.querySelector('.highlight');
var distance = document.querySelector('.highlight').getAttribute("data-howfar");
var direction = document.querySelector('.highlight').getAttribute("data-position");
var getPosition = function(distance, direction, node)
{
var i = 0;
var newNode = null;
if(direction == "prev"){
while (i < distance)
{
newNode = node.previousSibling;
if(newNode != null){
node = newNode;
if(newNode.nodeType != 3)
i++
}
else
{
i = distance
}
}
}
else
{
while (i < distance)
{
newNode = node.nextSibling ;
if(newNode != null){
node = newNode;
if(newNode.nodeType != 3)
i++
}
else
{
i = distance
}
}
}
return node;
}
var node = getPosition(distance,direction,highlighted.parentNode)
node.parentNode.insertBefore(addition,node);
strong { font-family:sans-serif; color:#f00000; }
.test-content { background: #f00000; color:#fff; padding:5px; }
<div class="content">
<p>
Lorem ipsum dolor sit amet, mel eu soluta adolescens, eu vel viris iudicabit definiebas, latine detracto lucilius id vis. Simul vituperata neglegentur qui ea, ex pri cibo alienum deleniti. Omnes omnesque democritum eam ea, est ut modo iriure laoreet. Possit luptatum scriptorem sed et, cu vitae audire corpora mea. Ea mea elitr tritani voluptaria, nostrud delectus ut cum. Ea per imperdiet splendide, duo ex mutat adhuc harum.
</p>
<p>
Usu suscipit necessitatibus no, sea at mazim ancillae scripserit. Nec ex facer petentium reprimique, qui ex tempor copiosae. Eum assum sensibus no. At sed vide paulo nostro, at modo postea officiis his, sale mundi aperiri at vel.
</p>
<p>
At vim civibus offendit, dolore persequeris vis ut. In eos dicant dissentiunt, cu causae epicurei est, natum veritus mnesarchum vim ex. An nam oportere adolescens. Ei diam modus iriure sed.
</p>
<p>
Cum liber dolorum fabellas id, vim dicta legimus in, natum perpetua signiferumque cum ea. In nibh viderer duo. Consul essent est ex, meis autem utinam eam ut. Quo ei errem quaestio temporibus.
</p>
<p>
Perfecto legendos pro no, vim ut imperdiet pertinacia. Te pri verear alterum, at atqui nostrud contentiones qui. Mel accumsan adolescens cu, quot singulis sea at, ex ius feugiat forensibus. Eu putent sanctus pro. No zril deserunt philosophia eum, id eum animal albucius electram, eum everti gubergren ne.
</p>
<p>
Lorem ipsum dolor sit amet, mel eu soluta adolescens, eu vel viris iudicabit definiebas, latine detracto lucilius id vis. Simul vituperata neglegentur qui ea, ex pri cibo alienum deleniti. Omnes omnesque democritum eam ea, est ut modo iriure laoreet. Possit luptatum scriptorem sed et, <strong class="highlight" data-position="prev" data-howfar="10">cu vitae audire corpora mea. Ea mea elitr tritani voluptaria,</strong> nostrud delectus ut cum. Ea per imperdiet splendide, duo ex mutat adhuc harum.
</p>
<p>
Usu suscipit necessitatibus no, sea at mazim ancillae scripserit. Nec ex facer petentium reprimique, qui ex tempor copiosae. Eum assum sensibus no. At sed vide paulo nostro, at modo postea officiis his, sale mundi aperiri at vel.
</p>
<p>
At vim civibus offendit, dolore persequeris vis ut. In eos dicant dissentiunt, cu causae epicurei est, natum veritus mnesarchum vim ex. An nam oportere adolescens. Ei diam modus iriure sed.
</p>
<p>
Cum liber dolorum fabellas id, vim dicta legimus in, natum perpetua signiferumque cum ea. In nibh viderer duo. Consul essent est ex, meis autem utinam eam ut. Quo ei errem quaestio temporibus.
</p>
<p>
Perfecto legendos pro no, vim ut imperdiet pertinacia. Te pri verear alterum, at atqui nostrud contentiones qui. Mel accumsan adolescens cu, quot singulis sea at, ex ius feugiat forensibus. Eu putent sanctus pro. No zril deserunt philosophia eum, id eum animal albucius electram, eum everti gubergren ne.
</p>
</div>
答案 2 :(得分:0)
如果您知道每个段落节点都相同,则此代码将起作用。基本上我循环遍历所有选定的段落节点,检查哪一个与突出显示的元素的父节点匹配。然后用一点逻辑来检查数据属性。
如果我理解你的需要,这个小提琴可以解决你的麻烦。
https://jsfiddle.net/9jjzksd3/
var addition = document.createElement('div');
addition.innerHTML = 'TEST CONTENT HERE';
addition.className = 'test-content';
var highlighted = document.querySelector('.highlight');
var pos = highlighted.getAttribute('data-position');
var howfar = parseInt(highlighted.getAttribute('data-howfar'));
var allNodes = document.querySelectorAll('.content > p');
var targetParent = highlighted.parentNode;
var targetParentIndex;
var insertIndex;
for(var i = 0; i < allNodes.length; i++){
if (allNodes[i] === targetParent){
targetParentIndex = i;
}
}
if(pos === 'prev') {
insertIndex = targetParentIndex - howfar;
} else {
insertIndex = targetParentIndex + howfar;
}
highlighted.parentNode.parentNode.insertBefore(addition, allNodes[insertIndex]);
如果这是你想要的,我个人会把这个逻辑抽象成它自己的帮助函数。希望这有帮助,请告诉我。