使用Angularjs动态生成之前/之后的CSS伪内容

时间:2015-08-25 16:08:47

标签: jquery css angularjs

我有一个div元素,需要动态地应用伪元素,例如之前和之后。我将从我的范围动态地将数据推送到css“content”元素。我怎么能用角度呢?

示例CSS

    .bar:before {
  content: 'dynamic before text';
    height: 20px;
    }
.bar:after {
  content: 'dynamic after text';
    height: 20px;
}

<div class="bar"></div>

3 个答案:

答案 0 :(得分:22)

您可以使用自定义data属性来保持其灵活性:

&#13;
&#13;
.bar::before,
.bar::after
{
  background-color: silver;
}

.bar::before
{
  content: attr(data-before-content)
}

.bar::after
{
  content: attr(data-after-content)
}
&#13;
<div class="bar" data-before-content="Hello" data-after-content="There">I have content</div>
<div class="bar" data-before-content="Hello">I have content</div>
<div class="bar" data-after-content="Different">I have content</div>
<div class="bar">I have content only</div>
&#13;
&#13;
&#13;

答案 1 :(得分:6)

您可以为内容使用动态html属性,如下所示: JSBin:http://jsbin.com/sepino/edit?html,css,js,output

<!DOCTYPE html>
<html ng-app="test">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <script language="JavaScript">
        angular.module('test',[]).controller('testController',function(){
            this.textbefore = 'left ';
            this.textafter = ' right';
        });
    </script>
    <style>
    .bar:before {
        content:  attr(data-textbefore);
        height: 20px;
    }
    .bar:after {
        content:  attr(data-textafter);
        height: 20px;
    }
    </style>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>
<body ng-controller="testController as myCtrl">
    <div class="bar" data-textbefore="{{myCtrl.textbefore}}" data-textafter="{{myCtrl.textafter}}">inside</div>
</body>
</html>

答案 2 :(得分:2)

您可以在内容字段中使用属性。我想你可以从中获取你需要的东西。

span:before {
   content: attr(data-content);
}