jQuery对html的捕获以及尺寸设置

1、jQuery HTML的设置与捕获

jQuery 中非常重要的部分,就是操作 DOM 的能力。

jQuery 提供一系列与 DOM 相关的方法,这使访问和操作元素和属性变得很容易

(1) html()

html() - 设置或返回所选元素的内容(包括 HTML 标记)。

$("#btn2").click(function(){

 alert("HTML: " + $("#test").html());

});

$("#btn2").click(function(){ 

$("#test2").html("<b>Hello world!</b>");

});

(2) text()

text() - 设置或返回所选元素的文本内容

$("#btn1").click(function(){ 

alert("Text: " + $("#test").text());

});

$("#btn1").click(function(){ 

$("#test1").text("Hello world!");

});

(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 + " 新文本: Hello world! (index: " + i + ")";

});

});

(5) attr()prop()

attr() prop()方法用于获取和返回属性值。

$("button").click(function(){ alert($("#runoob").attr("href")); });

$("button").click(function(){ $("#runoob").attr("href","http://www.runoob.com/jquery"); });

具有 true false 两个属性的属性,如 checked, selected 或者 disabled 使用prop(),其他的使用 attr().attr不仅可以返回(设置)元素的原生属性,还可以返回(设置)自定义属性。

 

1、jQuery HTML的页面尺寸操作

 

通过 jQuery,很容易处理元素和浏览器窗口的尺寸。

 

jQuery 尺寸

 

(1) width() height() 方法

 

width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)。

 

height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)。

 

$("button").click(function(){

 

"div 的宽度是: " + $("#div1").width() + "</br>";

 

    "div 的高度是: " + $("#div1").height(20);

 

});

 

(2) innerWidth() innerHeight() 方法

 

innerWidth() 方法返回元素的宽度(包括内边距)。

 

innerHeight() 方法返回元素的高度(包括内边距)

 

$("button").click(function(){

 

"div 宽度,包含内边距: " + $("#div1").innerWidth();

 

"div 高度,包含内边距: " + $("#div1").innerHeight();

 

});

 

(3) outerWidth() outerHeight() 方法

 

outerWidth() 方法返回元素的宽度(包括内边距和边框)。

 

outerHeight() 方法返回元素的高度(包括内边距和边框)。

 

$("button").click(function(){ 

 

txt+="div 宽度,包含内边距和边框: " + $("#div1").outerWidth() 

 

  txt+="div 高度,包含内边距和边框: " + $("#div1").outerHeight();

 

  });

 

(4) scrollTop() scrollLeft() 方法

 

scrollTop() 方法设置或者返回滚动条被卷去的元素的

 

scrollLeft() 方法设置或者返回滚动条被卷去的元素的宽度

 

$("button").click(function(){ alert($("div").scrollTop()); });

 

原文地址:https://www.cnblogs.com/guirong/p/13513418.html