Jquery-如何使用prop方法更改backgroundColor?
Can I change the backgroundColor property value using the prop method? I'm new to programming. :)
我可以使用prop方法更改backgroundColor属性值吗?我是编程新手。 :)
This is what I have,
这就是我所拥有的,
$('ul').prop('backgroundColor','red');
I read the chapters on this book I'm reading and it is my understanding that I can change properties from the DOM using the prop method in jquery. I can change other DOM properties such as className. Why not backgroundColor? Writing this I also tried atr.
我阅读了我正在阅读的这本书的章节,我的理解是我可以使用jquery中的prop方法从DOM中更改属性。我可以更改其他DOM属性,例如className。为什么不用backgroundColor?写这个我也试过atr。
$('ul').attr('background-color','red');
In this case, attr does have access to CSS properties, correct? However when using the prop method, we do have access to some CSS properties? Why is backgroundColor created?
在这种情况下,attr确实可以访问CSS属性,对吗?但是,在使用prop方法时,我们可以访问一些CSS属性吗?为什么创建backgroundColor?
I know the best way to go about changing the background color would be to use the css method, in jquery that is. I just wanted to know if or not the prop or atr method can change the background color, and why not, if not. I believe this will give me a better understanding of the DOM.
我知道改变背景颜色的最佳方法是在jquery中使用css方法。我只是想知道prop或atr方法是否可以改变背景颜色,为什么不改变背景颜色,如果没有。我相信这会让我更好地了解DOM。
Thanks!
谢谢!
4 个解决方案
#1
1
The backgroundColor
is nested property of style
property of the element so .prop('backgroundColor','red');
won't works here.
backgroundColor是元素的style属性的嵌套属性,所以.prop('backgroundColor','red');不会在这里工作。
Instead, you can set property by getting DOM element. In case there is multiple element then you need to iterate over them.
相反,您可以通过获取DOM元素来设置属性。如果有多个元素,那么您需要迭代它们。
$('div')[0].style.backgroundColor = 'red';
// if there is multiple elements
$('div').each(function() {
this.style.backgroundColor = 'red';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>a</div>
更多相关文章
- 使用表单字段值定制CSS属性。
- js获取html下拉框中选中值的自定义属性值
- 关于INPUT的autocomplete="off" 属性(浏览器表单默认的记忆功能)
- 关于 客户端发现响应内容类型为“text/html; charset=utf-8”,但
- HTML5新增标签与属性
- HTML5 Canvas 绘图方法整理 【十五、Canvas页面交互: 鼠标事件 】
- 不会出现Javascript context.closePath()方法
- CSS定位属性之间的相互作用
- Delphi下发送Email的方法