jQuery对象的Getter和Setter方法-下篇

版权声明:版权所有-江西服装学院 https://blog.csdn.net/qq_38263696/article/details/83026304

设置和获取元素内容

text(): 当不带参数调用时,text()返回所有匹配元素的所有后代文本节点(Text 3)的文本内容
html(): 获取或设置元素的html字符串, 会调用web解析器

获取和设置元素的位置高宽

offset( ) : 相对于文档坐标 , 返回一个{left: XXX , top: YYY } 对象, left代表X坐标 , top 代表Y坐标
offsetParent(): 相对于已定位的祖先元素或 , …;
width(), height() //注意 , 元素的CSS box-sizing属性 , 是context-box(内容盒模型) , 还是 border-box(边框盒模型)(width 包括边框,内边距的宽度)
innerWidth(), innerHeight()
outerWidth() , outerHeight()
scrollTop()和scrollLeft() :获取或设置滚动条的位置 , 不可接受函数参数;

获取和设置元素数据

data(): 获取或设置文档元素节点, Document和 Window对象相关联的数据.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>this is a test</title>
<style type="text/css">
	body{
		border-right: 10px solid red;
	}
</style>
	<!--小白注意引入脚本方法-->
	<script type="text/javascript" src="jquery-1.4.2.js"></script>
</head>

<body>
  <h1> <span>this</span></h1>
  <h1> is</h1>
  <h1> a</h1>
  <h1> test</h1>
  <p id="sprite" style="width: 100px; height: 60px; background-color: red;">How Are You</p>
  <div>1</div>
  <div class="nodata">2</div>
  <div id="mydiv">3</div>
  <div>4</div>

</body>
</html>
<script>
//获取元素内容
 console.log($("h1").text() ===" this is a test"); // true; 注意是匹配元素所有的文本内容
 console.log($("h1").html()===" <span>this</span>");  // true;  返回第一个匹配元素的: html字符串

//获取元素的位置高宽

var body =$("body");
var position =body.offset();
console.log(position);  //{left:8. top:8}


var paddings =body.innerWidth()-body.width() ; // 0 ;  body  的 左右padding的和  
var  borders = body.outerWidth()-body.innerWidth();  //0+10;    ;body  的  左右border 宽度的和  
var margins = body.outerHeight(true) - body.outerHeight() //8+8;   body 的 左右margin 的和

//获取和设置元素数据
  var html = $("html");
  html.data({contentType:"html5" ,author:"(^_^)" , WriteTime:"2018/10/12" });
  console.log(html.data('author'));  //"(^_^)"
  console.log(html.data());  //{contentType:"html5" ,author:"(^_^)" , WriteTime:"2018/10/12" }

</script>


![运行结果](https://img-blog.csdn.net/201810121421278?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4MjYzNjk2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

 

猜你喜欢

转载自blog.csdn.net/qq_38263696/article/details/83026304