javascript angularjs 将 css 属性添加到没有 jquery 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23069588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:16:18  来源:igfitidea点击:

angularjs add css property to element without jquery

javascriptcssangularjs

提问by user3339134

In an angular directive I am making a clone of the element that I want which is

在角度指令中,我正在制作我想要的元素的克隆

var node= element[0].cloneNode(true);

then I want to add css to this element. I know you can do this

然后我想将 css 添加到这个元素。我知道你可以做到这一点

$(node).css({width: width, left: left, height: height, top:'0px'});

but I know it is bad practice to use this in an angular directive. I have tried

但我知道在角度指令中使用它是不好的做法。我努力了

angular.node.css({width: width, left: left, height: height, top:'0px'});

but this does not work. I have scoured the internet and have found nothing. All I get is jquery ways. Does anyone know how to add css to an element the angular way?

但这不起作用。我已经搜索了互联网,但一无所获。我得到的只是jquery的方式。有谁知道如何以角度方式将 css 添加到元素?

To any help, thanks!

任何帮助,谢谢!

回答by Anthony Chu

Angular comes with jqLite, which is a trimmed down version of jQuery. There's nothing wrong with using it in a directive. clone()and css()are available in jqLite...

Angular 附带jqLit​​e,它是 jQuery 的精简版。在指令中使用它没有错。clone()并且css()在 jqLit​​e 中可用...

var node = element.clone()
                  .css({width: width, left: left, height: height, top:'0px'});

Working example: http://jsbin.com/yowubixa/1/edit?html,js,output

工作示例:http: //jsbin.com/yowubixa/1/edit?html,js,output

回答by phylax

ngStyledirective takes an "Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys."

ngStyle指令采用“表达式,该表达式对一个对象进行评估,该对象的键是 CSS 样式名称,值是这些 CSS 键的对应值。”

回答by user3339134

To those who may find this later, I found the solution to my problem. The reason why I could not do node.css() was because node was a dom element. This was due to my copy. To keep the javascript object you have to do

对于那些以后可能会发现这个问题的人,我找到了解决我的问题的方法。我不能做 node.css() 的原因是因为 node 是一个 dom 元素。这是由于我的副本。要保留您必须执行的 javascript 对象

angular.element(element[0]).clone() 

to properly clone it. this then allows me to do node.css(). You can do other things besides .css. You can look at the following here.

正确克隆它。这然后允许我做 node.css()。除了 .css 之外,您还可以做其他事情。您可以在此处查看以下内容。

http://docs.angularjs.org/api/ng/function/angular.element

http://docs.angularjs.org/api/ng/function/angular.element

Hope this helps!

希望这可以帮助!

回答by Rizo

open ....component.js

打开 ....component.js

angular.element(idName).css("background", "#000");

angular.element(idName).css("background", "#000");

i.e hello is idName in div.

即 hello 是 div 中的 idName。

<div id="hello"></div>

<div id="hello"></div>