我有一个自定义指令,它使用链接函数中元素的背景颜色:
.directive('ktMouseover', function($log) {
return {
restrict: "AC",
link: function(scope, elm, attrs) {
if ($(".ie8, .ie7").length === 0) {
console.log(elm.attr("class"));
var oldBackgroundColor = elm.css("background-color") || elm.css("background")
, colors = attrs["ktMouseover"].split("|")[0] || "#fec|#f55"
, timings = attrs["ktMouseover"].split("|")[1] || "75|150"
, newBackgroundColor = colors.split(":")[0] || "#fec"
, newDangerColor = colors.split(":")[1] || "#f55"
, fadeInTime = parseInt(timings.split(":")[0]) || 75
, fadeOutTime = parseInt(timings.split(":")[1]) || 150;
elm.mouseenter(function() {
if (elm.hasClass("inactive")) return;
$(this).animate({
"backgroundColor":($(this).hasClass("danger") ? newDangerColor : newBackgroundColor)
}, fadeInTime);
}).mouseleave(function() {
$(this).animate({
"backgroundColor": (oldBackgroundColor ? oldBackgroundColor : "transparent")
}, fadeOutTime);
});
}
}
};
})
HTML片段:
<li class="{{child.type()}}"
ng-include="'/partials/tree.html'"
id="container_{{child.id()}}"
kt-mouseover=":#f55|75:150"
ng-click="getChildren(child)"
ng-repeat="child in vault.children()">
</li>
当我最初对此进行编码时,我使用了标签的静态类名称(这就是我在css中设置背景颜色的方式)。现在我需要这些指令具有动态类名,这突然使得无法从元素中获取背景颜色,因为类名尚未应用于它。
如何在AngularJS中以惯用方式完成此操作?
答案 0 :(得分:1)
只需声明oldBackgroundColor变量而不初始化它,并在第一次将其设置在mouseenter中。我不知道这是否真的是最好的方法,但它确实有效:
.directive('ktMouseover', function($log) {
return {
restrict: "AC",
link: function(scope, elm, attrs) {
if ($(".ie8, .ie7").length === 0) {
// ***NOT INITIALIZED***
var oldBackgroundColor
, colors = attrs["ktMouseover"].split("|")[0] || "#fec|#f55"
, timings = attrs["ktMouseover"].split("|")[1] || "75|150"
, newBackgroundColor = colors.split(":")[0] || "#fec"
, newDangerColor = colors.split(":")[1] || "#f55"
, fadeInTime = parseInt(timings.split(":")[0]) || 75
, fadeOutTime = parseInt(timings.split(":")[1]) || 150;
elm.mouseenter(function() {
if (elm.hasClass("inactive")) return;
// ***INITIALIZED HERE INSTEAD***
if (!oldBackgroundColor) oldBackgroundColor = elm.css("background-color") || elm.css("background");
$(this).animate({
"backgroundColor":($(this).hasClass("danger") ? newDangerColor : newBackgroundColor)
}, fadeInTime);
}).mouseleave(function() {
$(this).animate({
"backgroundColor": (oldBackgroundColor ? oldBackgroundColor : "transparent")
}, fadeOutTime);
});
}
}
};
})