突出显示两个元素之间的所有文本

时间:2015-04-10 10:30:44

标签: javascript jquery html

鉴于以下示例html,我想突出显示两个图像标记之间的所有文本(通过添加css背景属性)。我尝试过使用jquerys .nextUntil()但是这只使用了第一个元素的兄弟节点,所以在这种情况下它不起作用。

编辑:下面的图像标签旨在成为不可见的占位符,表示在我的文本编辑器中具有相应ID的注释的起点和终点,中间的所有内容都是注释的焦点。

<div>
    <p>
        Lorem ipsum dolor
        <img class="commentBoundaryStart data-commentid="1" src="img.png"/>
          sit amet,"
    </p>
    <p>
        consectetur adipiscing elit. 
    </p>
    <h2>Header</h2>
    <p>
         Sed maximus laoreet augue
        <img class="commentBoundaryEnd" data-commentid="1" src="img2.png"/>
         , in ultrices sapien lobortis eu.
    </p>
    <p>
        Loremmmmm
    </p>
</div>

3 个答案:

答案 0 :(得分:1)

使用特定标记(imgp,深度不大),您可以执行以下操作:

&#13;
&#13;
// as you can't style text nodes, we first replace them
//  with span elements.
// This must be done only once and is independent of the
//  image markers
$('p').each(function(){
  var nodes = this.childNodes;
  for (var i=0; i<nodes.length; i++) {
    if (nodes[i].nodeType===3) {
      var text = nodes[i].textContent;
      var span = document.createElement("span");
      span.appendChild(document.createTextNode(text));
      this.replaceChild(span, nodes[i]);
    }
  }
});

// now, we colorize the first p
$('.commentBoundaryStart').nextUntil('.commentBoundaryEnd')
.css('color', 'red');

// the following ones
$('p:has(.commentBoundaryStart)')
.nextUntil(':has(.commentBoundaryEnd)').css('color', 'red');

// and the last one
$('p:has(.commentBoundaryEnd)').find('.commentBoundaryEnd')
.prevUntil('.commentBoundaryStart').css('color', 'red');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
    <p>
        "Lorem ipsum dolor"
        <img class="commentBoundaryStart" data-commentid="1" src="img.png"/>
        "  sit amet,"
    </p>
    <p>
        " consectetur adipiscing elit. "
    </p>
    <h2>Header</h2>
    <p>
        " Sed maximus laoreet augue"
        <img class="commentBoundaryEnd" data-commentid="1" src="img2.png"/>
        " , in ultrices sapien lobortis eu."
    </p>
    <p>
    </p>
</div>
&#13;
&#13;
&#13;

如果您的真实HTML更复杂,您可能需要调整代码。

当然最好使用addClass代替css,这样可以在移动或移除图片时更轻松地进行清理:只需执行$('span').removeClass('betweenMarks')

答案 1 :(得分:1)

这种情况的可能解决方案1.

它仅适用于图像之间的1 <p>个。如果你有超过1 <p>有nextAll而有些ifindexOf img或类似的东西,你需要稍微改变一下。

&#13;
&#13;
$(function() {

//coment start line
$('img.commentBoundaryStart').parent().contents().filter(function() {
  return this.nodeType == 3;
}).wrap('<span></span>');
$('img.commentBoundaryStart').next().css("background","red");

//middle lines
var has_returned = false;
$('img.commentBoundaryStart').parent().nextAll().each(function() {
    if (has_returned) { return; }
    if ($(this).contents().hasClass("commentBoundaryEnd")) {
        has_returned = true;
        return;
    } else {
        $(this).css("background","red");
    }
}); 

//end line
$('img.commentBoundaryEnd').parent().contents().filter(function() {
  return this.nodeType == 3;
}).wrap('<span></span>');
$('img.commentBoundaryEnd').prev().css("background","red");

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
    "Lorem ipsum dolor"
    <img class="commentBoundaryStart" data-commentid="1" src="img.png"/>
    "  sit amet,"
</p>
<p>
    " consectetur adipiscing elit. "
</p>
<p>
    " consectetur adipiscing elit. "
</p>
<span>
    " consectetur adipiscing elit. "
</span>
<p>
    " Sed maximus laoreet augue"
    <img class="commentBoundaryEnd" data-commentid="1" src="img2.png"/>
    " , in ultrices sapien lobortis eu."
</p>
<p>
</p>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

从这里的答案中汲取灵感后,我设计了自己的综合脚本,用于在无限深度和复杂性的html块中处理这个问题

&#13;
&#13;
$(function () {
    var root = $('#textarea-0001');
    var cid = 1;
    
    var startMarker = $("img.commentBoundary[data-commentid='" + cid + "']").first();
    var endMarker = $("img.commentBoundary[data-commentid='" + cid + "']").last();

    // Wrap start points siblings with span
    startMarker.parent().contents().filter(function() {
        return this.nodeType === 3;
    }).wrap("<span></span>");

    // Color its later siblings if they dont have the end point marker
    var has_done = false;
    startMarker.nextAll().andSelf().each(function() {
        if (has_done) {
            return;
        }
        if ($(this).has(endMarker).length > 0 || $(this).is(endMarker)) {
            has_done = true;
            return;
        } else {
            $(this).css("background-color", "rgba(128, 204, 255, 0.5)");
        }
    });

    // Get parents up to root
    var parentsList = startMarker.parentsUntil(root);

    if (parentsList.has(endMarker).length === 0) {
        // go through each of these and access later siblings
        var has_returned = false;
        parentsList.each(function() {
            $(this).nextAll().each(function() {
                if (has_returned) {
                    return;
                }
                if ($(this).has(endMarker).length > 0) {
                    has_returned = true;
                    return;
                } else {
                    $(this).css("background-color", "rgba(51, 173, 255, 0.5)");
                }
            });    
        });
    };


    // find end point marker
    var endPointContainer = root.children().has(endMarker);

    // Wrap end points siblings in spans
    endMarker.parent().contents().filter(function() {
        return this.nodeType === 3;
    }).wrap("<span></span>");

    // Color earlier siblings if they dont have start marker
    var is_done = false;
    $(endMarker.prevAll().andSelf().get().reverse()).each(function() {
        if (is_done) {
            return;
        }
        if ($(this).has(startMarker).length > 0 || $(this).is(startMarker)) {
            is_done = true;
            return;
        } else {
            $(this).css("background-color", "rgba(0, 122, 204, 0.5)");
        }
    });

    // Get parents up until end pointcontainer
    var parentsListEnd = endMarker.parentsUntil(endPointContainer);

    if (parentsListEnd.has(startMarker).length === 0) {
        // Go through each of these and access earlier siblings
        var is_returned = false;
        parentsListEnd.each(function() {
            $(this).prevAll().each(function() {
                if (is_returned) {
                    return;
                }
                if ($(this).has(startMarker).length > 0 || $(this).is(startMarker)) {

                    is_returned = true;
                    return;
                } else {
                    $(this).css("background-color", "rgba(0, 61, 102, 0.5)");
                }
            });

        });
    };
});

        
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <div id="textarea-0001">
            <p>
                Lorem ipsum dolor
                <img class="commentBoundary" data-commentid="1" src="img.png"/>
                  sit amet,
            </p>
            <p>
                <span> Hello! </span>
                <span>  consectetur adipiscing elit. </span>
                <h3>Header</h3>
            </p>
            <p>
                 consectetur adipiscing elit. 
            </p>
            <span>
                 consectetur adipiscing elit. 
            </span>
            <p>
                 Sed maximus laoreet augue
                <img class="commentBoundary" data-commentid="1" src="img2.png"/>
                 , in ultrices sapien lobortis eu.
            </p>
            <p>
            </p>
        </div>
&#13;
&#13;
&#13;