jQuery对html的获取以及对页面宽高的操作
1、对html的获取
(1)、html
html()-设置或返回所选元素的内容(包括HTMLHTML 标记/注释/属性/文本)。
$("#btn2").click(function(){
alert("HTML:"+$("#test").html());
});
$("#btn2").click(function(){
$("#test2").html("<b>Helloworld!</b>");
});
(2)、text
text()-设置或返回所选元素的文本内容。
$("#btn1").click(function(){
alert("Text:"+$("#test").text());
});
$("#btn1").click(function(){
$("#test1").text("Helloworld!");
});
(3)、val()
val()-设置或返回表单字段的值。
$("#btn1").click(function(){
alert("值为:"+$("#test").val());
});
$("#btn3").click(function(){
$("#test3").val("RUNOOB");
});
(4)、text()、html()以及val()的回调函数
上面的三个jQuery方法:text()、html()以及val(),同样拥有回调函数。回调函数有两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return"旧文本:"+origText+"新文本:Helloworld!(index:"+i+")";
});
});
(5)、attr()、prop()
attr()、prop()方法用于获取和返回属性值。 prop()设置或返回被选元素的属性。
$("button").click(function(){alert($("#runoob").attr("href"));});
$("button").click(function()
{$("#runoob").attr("href","http://www.runoob.com/jquery");});
注意:
prop()可以设置和返回备选元素的本身属性,但是自定义属性不行具有true和false两个属性的属性,如checked,selected或者disabled使用prop(),其他的使用attr();.attr不仅可以返回(设置)元素的原生属性,还可以返回(设置)自定义属性。
2、对页面宽高的操作
(1)、width()和height()方法
width()方法设置或返回元素的宽度(不包括内边距、边框或外边距)。==width
height()方法设置或返回元素的高度(不包括内边距、边框或外边距)。==height
$("button").click(function(){
"div的宽度是:"+$("#div1").width()+"</br>";
"div的高度是:"+$("#div1").height(20);
});
(2)、innerWidth()和innerHeight()方法
innerWidth()方法返回元素的宽度(包括内边距)。==clientWidth
innerHeight()方法返回元素的高度(包括内边距)。==clientHeight
$("button").click(function(){
"div宽度,包含内边距:"+$("#div1").innerWidth();
"div高度,包含内边距:"+$("#div1").innerHeight();
});
(3)、outerWidth()和outerHeight()方法
outerWidth()方法返回元素的宽度(包括内边距和边框)。==offsetWidth
outerHeight()方法返回元素的高度(包括内边距和边框)。==offsetHeight
$("button").click(function(){
txt+="div宽度,包含内边距和边框:"+$("#div1").outerWidth()
txt+="div高度,包含内边距和边框:"+$("#div1").outerHeight();
});
(4)、scrollTop()和scrollLeft()方法
scrollTop()方法设置或者返回滚动条被卷去的元素的高度
scrollLeft()方法设置或者返回滚动条被卷去的元素的宽度
$("button").click(function(){alert($("div").scrollTop());});