jq 操作元素样式

短命女 2021-07-24 14:35 528阅读 0赞
  1. **返回css样式内容**
  2. 对象数组.css("样式名")
  3. function t2()
  4. {
  5. var showdiv=$("#showdiv");
  6. alert(showdiv.css("width"));
  7. }
  8. js.style方法不能获取写在css代码域内的样式
  9. **增加/修改样式**
  10. 数值可以不加px,如要加需要'400px' 括起来
  11. 对象数组.css("样式名","修改样式")
  12. function t1()
  13. {
  14. var showdiv=$("#showdiv");
  15. //操作样式
  16. showdiv.css("background-color","red");
  17. }
  18. 在原值基础上修改
  19. 对象数组.css('样式名','+=200'); 在原来基础上增加200px
  20. **增加多个样式**
  21. 数值可以不加px,如要加需要'400px' 括起来
  22. 对象数组.css({"样式名":"样式值","样式名":"样式值","样式名":"样式值"...})
  23. function t3()
  24. {
  25. var div=$("#div01");
  26. div.css({"border":"solid 2px orange","width":"300px","height":"200px"});
  27. }
  28. **通过类选择器添加样式**
  29. 对象数组.addClass("类选择器名")
  30. function t4()
  31. {
  32. var div=$("#div01");
  33. div.addClass("common");
  34. }
  35. **移除类选择器样式**
  36. 对象数组.removeClass("类选择器名")
  37. function t5()
  38. {
  39. var div=$("#div01");
  40. div.removeClass("common");
  41. }

代码示例:

  1. <html>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>jq 操作元素样式</title>
  5. <script type="text/javascript" charset="utf-8" src="js/jquery-3.4.1.js"></script>
  6. <script type="text/javascript">
  7. function t1()
  8. {
  9. var showdiv=$("#showdiv");
  10. //操作样式
  11. showdiv.css("background-color","red");
  12. }
  13. function t2()
  14. {
  15. var showdiv=$("#showdiv");
  16. alert(showdiv.css("width"));
  17. }
  18. function t3()
  19. {
  20. var div=$("#div01");
  21. div.css({ "border":"solid 2px orange","width":"300px","height":"200px"});
  22. }
  23. function t4()
  24. {
  25. var div=$("#div01");
  26. div.addClass("common");
  27. }
  28. function t5()
  29. {
  30. var div=$("#div01");
  31. div.removeClass("common");
  32. }
  33. </script>
  34. <style type="text/css">
  35. #showdiv{
  36. width:100px;
  37. height:200px;
  38. border:solid 2px;
  39. }
  40. .common{
  41. width:100px;
  42. height:200px;
  43. border:solid 2px;
  44. background-color: purple;
  45. }
  46. </style>
  47. </head>
  48. <body>
  49. <input type="button" value="修改样式" onclick="t1()"/>
  50. <input type="button" value="返回样式" onclick="t2()"/>
  51. <input type="button" value="操作多个样式" onclick="t3()"/>
  52. <input type="button" value="操作类选择器" onclick="t4()"/>
  53. <input type="button" value="移除类选择器样式" onclick="t5()" />
  54. <hr/>
  55. <div id="showdiv" >
  56. </div>
  57. <div id="div01" class="common">
  58. </div>
  59. </body>
  60. </html>

发表评论

表情:
评论列表 (有 0 条评论,528人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JQ DOM操作

    今天开始学习李炎恢老师JQ视频中有关DOM操作的相关方法,在此记录下学习过程,以便日后回来复习! 首先是一些对元素内容的操作,大体分为3个方法 `html(),text