【问题标题】:select specific strings inside a DIV and format it选择 DIV 中的特定字符串并对其进行格式化
【发布时间】:2013-12-20 13:21:51
【问题描述】:

div 内的示例文本:

I am at the first line.
I am at the second line.
I am at the third line.
I am at the end of the first paragraph.

问题: 我想制作一个脚本:

  1. 所有“第一”都将被涂成蓝色
  2. 所有“第二个”都将被涂成绿色
  3. 所有“第三个”都将被涂成红色和粗体

Please see the non working code here..

添加了代码链接

【问题讨论】:

  • 你的代码在哪里?这里的人会帮助你,但不会为你写代码。
  • 澄清一下:您在 DIV 中有一些纯文本,您需要设置第一、第二和第三个句子的样式(不管前 3 个后面有多少个句子)?句子可以以句号以外的形式结尾吗?正如 user1743214 建议的那样,您可以控制文本吗?您可以在 HTML 元素中预先包装该文本吗?另外,正如 Steve-Wellens 建议的那样,您能提供任何标记或代码吗?谢谢!

标签: jquery css html


【解决方案1】:

给你

$(function(){   
  $('#text').attr('value','first').css('color','#0000FF');
  $('#text').attr('value','second').css('color','#00FF00');
  $('#text').attr('value','third').css('color','#FF0000');
  $('#text').attr('value','third').css('font-weight','bold');
});

【讨论】:

    【解决方案2】:

    这几乎是不可能实现的,如果适用于一个文章或段落,它不会适用于另一个.. 在我看来,唯一的解决方案是包含一个 html 标记,该标记将定义这些标记,然后为它们应用 jquery 代码,

    <p class='paragraph'>
    <span class='firstline'>This is the first line.</span>
    <span class='secoundline'> This is the second line. </span>
    <span class='thirdline'> This is the third line.</span>
    <span class='endparagraph'>This is the end of the first paragraph.</span>
    </p>
    

    现在在 jquery 部分你可以做类似的事情

    $(function(){
      $('.firstline').css({'color':'blue' , 'font-weight':'bold'});
      .....
    
    })
    

    【讨论】:

    • 这些文本在 div 中。这里:
      这是第一行。这是第二行。这是第三行。这是第一段的结尾。
    • 对不起,但我怎么知道...除了它们是否在 div 内或其他任何地方都没有关系,您只需要放置正确的标记
    【解决方案3】:

    您可以使用 jQuery :nth-child 选择器来做到这一点。您可以使用 css() 或通过向段落添加类并使用 CSS 设置样式(这将是理想的)来应用样式。

    我创建了一个具有两个版本的 JSFiddle:http://jsfiddle.net/RJ8sC/5/。您只需将包装器 div ID 更改为您的 ID,就可以开始了。

    这里是快速参考的 jQuery 代码:

    $(document).ready( function() {
        $('#example p:nth-child(1)').css('color','blue');
        $('#example p:nth-child(2)').css('color','green');
        $('#example p:nth-child(3)').css({color:'red', 'font-weight': 'bold'});
    });
    
    // ALTERNATIVE USING CLASSES - THIS IS BETTER PRACTICE
    
    $(document).ready( function() {
        $('#example2 p:nth-child(1)').addClass('first');
        $('#example2 p:nth-child(2)').addClass('second');
        $('#example2 p:nth-child(3)').addClass('third');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多