2

This is a continuation of What's a good way to show parts of an element but hide the rest?

<h1>
  Let's say you had this <span class="safe">text</span>.
</h1>

How could one wrap all non-safe regions in an element with a disappear class (with jQuery).

Final Output

<h1>
  <span class="disappear">Let's say you had this </span>
  <span class="safe">text</span>
  <span class="disappear">.</span>
</h1>

That way, the parent node is still visible, but the non-safe regions disappear, leaving the safe.

I'm not sure how to do this, but surely it's possible.

4

4 回答 4

6

文本节点的 anodeType为 3。迭代节点并用于wrap()包装文本节点。:

$someElement.contents().each(function() {
    if (this.nodeType == 3)
        $(this).wrap('<span class="disappear" />');
});

http://jsfiddle.net/SnjnJ/

于 2013-08-29T21:17:28.847 回答
5

过滤 textNodes 并将它们包装在 spans 中:

$('h1').contents().filter(function() {
    return this.nodeType === 3;
}).wrap('<span class="disappear" />');

小提琴

于 2013-08-29T21:18:14.203 回答
2
$('h1').children().not('.safe').hide(); 

http://jsfiddle.net/VeSCw/

于 2013-08-29T21:20:05.990 回答
0

匹配所有内容h1并使用从您的选择.not()中删除。safe然后使用.wrap()使它们“消失”。

http://api.jquery.com/not/

于 2013-08-29T21:15:56.647 回答