用jquery从段落中随机加粗2个单词

时间:2017-10-10 10:57:44

标签: javascript jquery

我正在寻找类似于松弛的帮助中心https://get.slack.help/hc/en-us/categories/200111606

上可以看到的内容

他们成功地做到了这一点,并且看起来每个类别描述都有两个或三个粗体的随机单词。

我试过这个:

  //testing random words

  var words = $('.blocks-item-description').text().split(' ');

// with help from http://stackoverflow.com/questions/5915096/get-random-item-from-array-with-jquery

var randomWord = words[Math.floor(Math.random()*words.length)];

// with more help from http://stackoverflow.com/questions/2214794/wrap-some-specified-words-with-span-in-jquery

$('.blocks-item-description').html($('.blocks-item-description').html().replace(new RegExp( randomWord, 'g' ),'<strong>'+randomWord+'</strong>'));

并在此处测试:https://doculus.zendesk.com/hc/en-us(不是我的网站),但我无法看到相同的结果。

感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:0)

Slack制作大胆的关键词。例如:登录松弛

但如果你真的需要加粗随意的话:

<span></span>包裹每个单词并将其中一些类应用于粗体。

$(document).ready(function() {
  $('#text').html('<span>' + $('#text').text().replace(/ /g, '</span> <span>') + '</span>');

  for (var i = 0; i < 5; i++) {
    $('#text span').eq(Math.floor(Math.random() * $('#text span').length)).addClass('bold');
  }
});
.bold {
  font-weight: bold;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi commodo ante et pharetra iaculis. Nam eget nunc convallis est finibus sollicitudin id at leo. Nullam convallis eros vitae pellentesque molestie. Aliquam facilisis porta lorem in congue. Proin
  ac neque elementum, placerat neque et, dictum ex. Nulla commodo, justo eu lacinia ultrices, sem lectus consequat lacus, sed tempor nibh tellus in enim. Quisque tincidunt odio magna, vel rhoncus mi condimentum eu. Ut nec dolor scelerisque ligula elementum
  pharetra. Fusce rutrum vel ipsum id tristique. Donec vestibulum maximus magna, quis vehicula magna pretium ut. Maecenas vel nunc ex. Proin dui lacus, ullamcorper vitae blandit sed, placerat ac neque. Orci varius natoque penatibus et magnis dis parturient
  montes, nascetur ridiculus mus. Vivamus vel augue at neque aliquet elementum luctus vel erat.
</div>