如何在剃须刀视图中更改第一个字母的颜色?

时间:2017-08-19 16:27:27

标签: css asp.net-mvc razor

我正在asp.net的一些博客网站上工作。使用剃刀布局页面显示数据库中的所有内容数据。内容部分的第一段保留给某些子标题,并获得字体大小,颜色等首字母的样式规则。



#post-content .blog-post p:first-child {
  font-size: 1.85em;
  line-height: 1.4em;
}

#post-content .blog-post p:first-child:first-letter {
  color: #43464b;
  float: left;
  font-size: 2.85em;
  font-weight: 700;
  margin: 6px 8px -5px 0;
  line-height: 60px;
}

<section id="post-content" class="b-container">

  <div class="blog-post">
    @*first paragraph reserved for title*@
    <p>
      @Model.PostSubhead1

    </p>
    @*first paragraph end*@
    <p>
      @Model.PostText1
    </p>
    <figure>
      <img src="@Url.Content(Model.PostBigImage1)" class="big-image" />
      <em class="img-text">
                   @Model.PostBigImageText1
                </em>
    </figure>

  </div>
</section>
&#13;
&#13;
&#13;

如何从数据库中设置first-letter的颜色?因为每个帖子的标题中的第一个字母都有不同的颜色。

1 个答案:

答案 0 :(得分:0)

不幸的是,您无法使用内联CSS实现伪效果。

这个问题的一个(糟糕的)解决方法是让你的js在需要时添加样式块。例如:

var colors = ["#6e2d5b", "#b2a9e9", "#489b34", "#5765a9"];
var i = 0;
function addArticle() {
  i++;
  //get the color and put it in a var named color
  var color = colors[i%4];
  //generate a custom classname and put it in a var named customClass
  var customClass = "_" + color.substr(1);
  var articles = document.getElementById("articles");
  var article = document.createElement("div");
  article.className = customClass;
  article.innerHTML = "content goes here";
  articles.appendChild(article);
  var css = "." + customClass + "::first-letter{color: " + color + ";} ";
  document.getElementById("style").appendChild(document.createTextNode(css));
}
<style id="style">

</style>
<div id="articles">
</div>
<button onclick="addArticle();">add an aricle</button>