【问题标题】:Can I use AngularJs Directives to apply a style to a pseudo Element我可以使用 AngularJs 指令将样式应用于伪元素吗
【发布时间】:2014-06-11 03:56:18
【问题描述】:

我希望我不会在这里遗漏一些明显的东西,但我正在尝试学习 Angular,但在尝试制定指令时遇到了问题。

我正在尝试构建一个指令,该指令将从数据属性(“背景图像”)中获取 url,并将其作为背景图像应用于伪元素,但我无法确定如何定位::before 元素,或者即使 Angular 可以修改伪元素。

这是我正在尝试构建的指令: http://cdpn.io/cqvGH

我可以让它将背景应用到 div.item 但是当我尝试定位 ::before no joy.

这是指令代码:

angular.module('testApp', [
])

angular.module('testApp')
  .directive('backgroundImage', function(){
    return function(scope, element, attrs){
        restrict: 'A',
        attrs.$observe('backgroundImage', function(value) {
      // If I remove ::before it will apply image background to .item correctly.
        element::before.css({
                'background-image': 'url(' + value +')'
            });
        });
    };
});

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

    这很棘手,但有可能。尝试类似:

     var style = "<style>.item:before{background-image:url("+value+")}</style>"
     angular.element("head").append(style);
    

    在这里工作:http://codepen.io/anon/pen/Difrt

    【讨论】:

    • 哇,太棒了!我还有一个障碍,因为现在如果我尝试拥有多个项目,则样式不会内联应用于元素,我不能两者都将具有相同的背景图像,因为背景设置为类 .item。有没有办法我可以做到这一点,但它可以与多个元素一起使用,每个元素都有不同的背景图像?
    • Cherniv 对于我的原始问题是绝对正确的,他的代码创建了 ::before 元素但是如果想将图像应用于多个项目,您还可以将背景图像应用于一个跨度是我决定要做的(如果有人有办法在我全神贯注之前使用 ::before 进行此操作),否则此链接将向您展示我是如何做到的。 cdpn.io/cqvGH
    • @Daimz 你可以通过添加动态和唯一的“id”来做到这一点,看看:codepen.io/anon/pen/enHxq
    猜你喜欢
    • 2011-07-25
    • 1970-01-01
    • 2016-11-20
    • 2012-11-13
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多