Fork me on GitHub

jQuery中的CSS-DOM操作

html代码

  1. <p style="color:blue;">武汉PHP培训-武汉长乐教育</p>

css()方法

  1. $("p").css("color") //获取颜色样式
  2. $("p").css("color", "red"); //设置样式
  3. $("p").css({"color":"red", "font-size":"20px"});

height()和width()方法

  1. $("p").height(); //获取高度
  2. $("p").height("100px"); //设置高度
  3. $("p").width(); //获取宽度
  4. $("p").width("400px") //设置宽度

offset()方法

  1. var offset = $(".children").offset(); //获取元素在当前视窗的相对偏移
  2. //console.log(offset)
  3. var left = offset.left; //获取左偏移
  4. var top = offset.top; //获取上偏移

position()方法

  1. var position = $(".children").position(); //获取relative或absolute元素的祖先节点相对偏移
  2. var left = position.left; //获取左偏移
  3. var top = position.top; //获取上偏移

下面看例子

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>
  5. <meta charset="utf-8">
  6. <style type="text/css">
  7. .parent{
  8. width: 500px;
  9. height: 500px;
  10. border: 1px solid;
  11. position: relative;
  12. top:100px;
  13. left:300px;
  14. }
  15. .children{
  16. width: 100px;
  17. height: 100px;
  18. border: 1px solid #08c;
  19. position: absolute;
  20. top:100px;
  21. left:300px;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div class="parent">
  27. <div class="children"></div>
  28. </div>

scrollTop()方法和scrollLeft()方法

  1. <html>
  2. <head>
  3. <title></title>
  4. <meta charset="utf-8">
  5. <style type="text/css">
  6. .parent{
  7. width: 200px;
  8. height: 200px;
  9. border: 1px solid;
  10. overflow: auto;
  11. }
  12. .children {
  13. width: 500px;
  14. height: 500px;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="parent">
  20. <div class="children">
  21. scrollTop()方法和scrollLeft()
  22. </div>
  23. </div>
  24. <button class="button1">获取scrollTop</button><br>
  25. <button class="button2">设置scrollTop</button>
  26. <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  27. <script type="text/javascript">
  28. $(function(){
  29. $(".button1").click(function(){
  30. var scrollTop=$("div").scrollTop(); //获取元素滚动条距离上面的位置
  31. var scrollLeft=$("div").scrollLeft(); //获取元素滚动条距离左边的位置
  32. })
  33. $(".button2").click(function(){
  34. $("div").scrollTop(200); //设置元素滚动条距离上面的位置
  35. $("div").scrollLeft(200); //设置元素滚动条距离左边的位置
  36. })
  37. })
  38. </script>
  39. </body>
  40. </html>
posted @ 2018-10-25 14:09  big2cat  阅读(400)  评论(0)    收藏  举报