0

我确信这是一个简单的问题。我有一些随机化引号的javascript,但我希望引用和引用的作者是不同的颜色。我当然可以使用 CSS 来更改所有文本的外观,但是我没有太多运气将引用和作者分开,而且我对 javascript 也不是很精通。

<script language="JavaScript">

var Quotation=new Array()

Quotation[0] = "Only two things are infinite, the universe and human stupidity, and I'm    not sure about the former.<br>Albert Einstein";
Quotation[1] = "Science is a way of thinking much more than it is a body of knowledge. <br>Carl Sagan";
Quotation[2] = "Few tragedies can be more extensive than the stunting of life, few injustices deeper than the denial of an opportunity to strive or even to hope, by a limit imposed from without, but falsely identified as lying within.<br>Stephen Jay Gould";
Quotation[3] = "I don't want to talk to you no more, you empty-headed animal food trough wiper! I fart in your general direction! Your mother was a hamster and your father smelt of elderberries!<br>Taunting Frenchman";

var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){document.write(Quotation[whichQuotation]);}
showQuotation();
</script>
4

3 回答 3

0

如果引号肯定是您从中获取样本的格式,则按
标签拆分每个引号并在其周围附加跨度,如下所示:

var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation(){
  var Quote = Quotation[whichQuotation];
  var quoteColor = 'green';
  var authorColor = 'red';
  var quoteSplits = Quote.split('<br>');
  var Quote = '<span style="color:' + quoteColor + '">' + quoteSplits[0] + '</span><br>';
      Quote += '<span style="color:' + authorColor + '">' + (quoteSplits.length > 1 ? quoteSplits[1] : '') + '</span>'; 
  document.write(Quote);
}
showQuotation();
于 2013-08-21T05:20:36.047 回答
0

只需将您想要单独颜色的文本部分包含在<span></span>具有不同样式的标签中即可。

例如

Quotation[0] = "<span style='color:green'>Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.</span><br><span style='color:red'>Albert Einstein</span>";

于 2013-08-21T05:03:03.593 回答
0

让引号和作者在 HTML 本身中具有不同的跨度和公共类,然后通过 jQuery将样式应用于每个类。

这是一个例子:

<span class="jQuote">Some blah blah stuff</span> <br />
<span class="jAuthor">Mr. Somebody</span>

在 Javascript 中:

$(function(){
  $(".jQuote").css(/*Whatever styles you need to apply*/);
  $(".jAuthor").css(/*Whatever styles you need to apply*/);
});  

了解更多关于通过 jQuery 使用css的信息。

但更好的方法是将不同的类应用于引用和作者,并通过 CSS 应用样式。

于 2013-08-21T05:11:51.077 回答