jquery修改style样式的某个属性(jquery添加属性的方法)

发布日期:2025-02-02 03:06:36     手机:https://m.xinb2b.cn/baike/news53944.html    违规举报
核心提示:js插件jquery可以很方便的对HTML的元素进行操作,比如一些元素的显示与隐藏,一些元素的动态效果等,今天就说一说通过jquery获取DIV元素的CSS属性,以及设置DIV元素的CSS属性的方法。 jquery获取DIV元素的CSS属性

js插件jquery可以很方便的对HTML的元素进行操作,比如一些元素的显示与隐藏,一些元素的动态效果等,今天就说一说通过jquery获取DIV元素的CSS属性,以及设置DIV元素的CSS属性的方法。

jquery获取DIV元素的CSS属性值

jq获取DIV元素的属性值,可以使用css()方法

例:利用jquery获取DIV元素的宽

<!DOCTYPE html><html><head> <title>document</title> <style> #mochu{ margin: 10px; padding: 10px; color: red; height: 30px; width: 40px; } </style> <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script></head><body> <div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div> <script> var h = $(\'#mochu\').css(\'width\'); console.log(h); </script></body></html>

打印结果:

40px

例:利用jquery获取DIV元素的高

<!DOCTYPE html><html><head> <title>document</title> <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script></head><body> <div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div> <script> var h = $(\'#mochu\').css(\'height\'); console.log(h); </script></body></html>

打印结果:

42px

注意:

1、如果给DIV元素定义了CSS属性的值,则直接输出定义的CSS值

2、如果未定义DIV元素的CSS属性值,则输出浏览器渲染后DIV的默认值

利用jquery设置DIV元素的值

在JQ中可以通过CSS方法获取DIV元素的CSS属性值,也可以设置或改变元素的CSS属性值

例:利用jq改变字体的颜色

<!DOCTYPE html><html><head> <title>document</title> <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script></head><body> <div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div> <script> $(\'#mochu\').css(\'color\',\'red\'); </script></body></html>

结果如图:

注:改变DIV中字体的颜色其实就是给这个DIV加入了一个 color 的CSS属性,并把属性值设置成 red(红色)

在浏览器中查看元素就可以发现加入的CSS属性

例:给DIV元素加入多个CSS属性

<!DOCTYPE html><html><head> <title>document</title> <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script></head><body> <div id="mochu">飞鸟慕鱼博客<br/>http://www.feiniaomy.com</div> <script> $(\'#mochu\').css({\'color\':\'red\',\'heigth\':\'40px\',\'width\':\'40px\'}); </script></body></html>

在浏览器中审核元素,如下图

可以发现,对过JQ设置的CSS属性都写到了DIV上

注意:利用JQ的CSS()方法设置或添加多个CSS属性的时候,要以{”:”,”:”}这种数据格式写入。

 
 
本文地址:https://xinb2b.cn/baike/news53944.html,转载请注明出处。

推荐图文
推荐百科经验
网站首页  |  关于我们  |  联系方式  |  使用协议  |  版权隐私  |  网站地图  |  违规举报  |  蜀ICP备18010318号-4  |  百度地图  | 
Processed in 0.083 second(s), 80 queries, Memory 0.51 M