【问题标题】:Adding specific words to a class? [duplicate]将特定单词添加到课程中? [复制]
【发布时间】:2014-08-03 21:45:04
【问题描述】:

我想在类文件中添加单词,我可以为文档的其余部分设置某种样式

例如:

我想将单词“the”设置为一个名为 cross 的类

CSS

.cross {
    font-style:italic
}

会发生什么: “那个人走到了家商店。”

这可能吗?或者是否有另一种方式来设置整个文档中每次使用“the”这个词的样式?

【问题讨论】:

  • 我想,“the”这个词应该是某种带有类交叉的
  • @TJ,是的,这个问题的条件完全相同,使用 javascript 来实现。某种突出显示。

标签: javascript jquery html css


【解决方案1】:

试试这个;

   var text = 'the';
    $('*').html( function ( i, html ) {
        var regexp, replacement;
        regexp = RegExp( '(' + text + ')', 'gi' );
        replacement = '<span class="cross">$1</span>';
        return html.replace( regexp, replacement );
    });

【讨论】:

  • 我添加了一个JSFiddle 以表明这确实有效
【解决方案2】:

你应该像这样遍历每个单词:

var tokens = text.split(" ");
for(var i=0; i < tokens.length; i++){
    if(tokens[i] == "the"){
        tokens[i] = "<span class='cross'>the</span>";
    }
}
$(elem).html(tokens.join(" "));

【讨论】:

    【解决方案3】:

    这个怎么样:

    演示:http://jsfiddle.net/4MrCV/3/

    HTML:

    <div id="mytext">the man walked to the shops not their shop.</p>
    

    JavaScript:

    var $t = $("#mytext");
    $t.html($t.text().replace(/the /gi,"<span class='cross'>$&</span>"));
    

    希望这会有所帮助。

    【讨论】:

    • 这很好,但您应该修改它以排除其中包含 the 的文本,例如 theretheir 等。
    【解决方案4】:

    通常您会使用span 来设置单词的样式

    <p><span class="cross">the</span> man walked to <span class="cross">the</span> shops.</p>
    

    【讨论】:

    • 每次在整个文档中使用“the”这个词的样式
    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2023-04-10
    • 2017-03-03
    • 2018-03-16
    • 2020-10-14
    • 2020-09-19
    相关资源
    最近更新 更多