【问题标题】:ng-style and javascript object with the same named properties具有相同命名属性的 ng-style 和 javascript 对象
【发布时间】:2013-06-27 00:31:15
【问题描述】:

你们是怎么处理这种情况的:

<div ng-style='currentStyle'>

scope.currentStyle = {
   "background": "-moz-linear-gradient(top, " + colorFrom + " 0%, " + colorTo + " 100%)",
   "background": "-webkit-gradient(linear, left top, left bottom, color-stop(0%, " + colorFrom + "), color-stop(100%," + colorTo + "))",
   "background": "-webkit-linear-gradient(top,  " + colorFrom + " 0%," + colorTo + " 100%)",
   "background": "-o-linear-gradient(top,  " + colorFrom + " 0%," + colorTo + " 100%)",
   "background": "-ms-linear-gradient(top,  " + colorFrom + " 0%," + colorTo + " 100%)",
   "background": "linear-gradient(to bottom,  " + colorFrom + " 0%," + colorTo + " 100%)"
}

如果似乎拥有具有相同命名键的 javascript 对象是错误的,不是吗? 那么如何制作渐变样式呢?

upd:我不知道,也许像这样的 javascript 对象没有什么问题(在我的浏览器中工作),但是咖啡脚本编译器抱怨这样的代码,说:名为“背景”的多个对象文字属性

【问题讨论】:

  • 在coffeescript中运行良好,因为它不会抱怨。当然,您不能多次拥有相同的密钥。
  • 嗯,是的,最近确实如此,问题是我的同事正在使用一个使用旧编译器的 VS 扩展,它确实抱怨
  • 我使用ng-class 来处理它 :)
  • 是的,但如果您注意到它是一种计算样式,颜色值会在运行时发生变化。不能将这样的东西粘贴到 .css 中

标签: javascript css angularjs


【解决方案1】:

如果你避免使用 ngStyle 指令并直接使用会怎样:

<div style='{{currentStyle}}'></div>

这样您就可以将样式声明创建为纯 CSS 中的字符串。

$scope.currentStyle = "background: -moz-linear-gradient(top, " + colorFrom + " 0%, " + colorTo + " 100%);"
[etc....]

【讨论】:

  • 我知道它没有那么优雅。如果你想要更漂亮的东西,可以写一个特殊的指令来处理你的渐变代码?
  • 是的,你说得对,可能最好有一个指令,如果我发现自己再次使用同样的东西,我一定会把它变成一个指令
猜你喜欢
  • 2016-01-04
  • 2013-10-14
  • 2017-02-28
  • 2018-10-24
  • 2020-02-22
  • 2013-06-16
  • 2017-02-27
  • 2021-02-02
相关资源
最近更新 更多