【问题标题】:How to style only single word of a WordPress post title如何仅设置 WordPress 帖子标题的单个单词的样式
【发布时间】:2014-11-12 11:12:10
【问题描述】:

我想知道我是否可以在 wordpress 中仅对帖子标题中的一个单词进行样式设置,例如在两者之间添加跨度。但是 Wordpress 将标题作为一个整体呈现,并且找不到如何做到这一点。

例如:标题可以是“你好,欢迎来到这个世界” 在这里,我想对像“欢迎”这样的单个词进行不同的样式设置。

我的标题 HTML 模板是这样的

<h2>Hello, <span>welcome</span> to this world</h2>

但在 wordpress 中,我们只能完全检索标题,使用

the_title();

标签。输出会像

<h2>Hello, welcome to this world</h2>

我怎样才能做到这一点?

提前致谢

【问题讨论】:

  • 模式是什么?如果你想自动化,就必须有一个模式。

标签: jquery html css wordpress wordpress-theming


【解决方案1】:

一种方法,使用原生 JavaScript:

function h1Words() {
  // finding the first/only <h1> element:
  var h1 = document.querySelector('h1'),
    // working out whether we can use textContent or innerText to access the text:
    textProp = 'textContent' in document ? 'textContent' : 'innerText',
    // a simple counter:
    wordNum = 1;

    // setting the innerHTML of the <h1> element
       // accessing the text of the <h1>,
       // splitting that text on word-boundary characters (/\b/) with
       // split() using a regular expression,
       // iterating over the resuls using map(), 'chars' is the array-element:
       // if the 'chars' variable is a string of alpha-numerics (/^w+$/)
       // we wrap that sequence in a <span> element (with classes),
       // otherwise we return the 'chars' unchanged:
    h1.innerHTML = h1[textProp].split(/\b/).map(function(chars) {
      return (/^\w+$/).test(chars) ? '<span class="word word' + wordNum+++'">' + chars + '</span>' : chars;
    // joining the array-elements back together to re-form a string:
    }).join('');
}

h1Words();
h1 .word {
  color: rgba(200,200,200,0.6);
}

h1 .word3 {
  color: orange;
}

h1 .word:nth-child(1) {
  color: green;
}
&lt;h1&gt;Hello, welcome to this world&lt;/h1&gt;

参考资料:

【讨论】:

  • +1 为一个解释不清的问题提供创造性的答案。
【解决方案2】:

使用 css 我们可以做到这一点。

    h2 > span{color:red;}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2021-06-04
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    相关资源
    最近更新 更多