1. html和text操作
$("#box").html(); //获取html内容
$("#box").text(); //获取文本内容
$("#box").html("<em>www.ycku.com</em>"); //设置html内容
$("#box").text("www.ycku.com"); //设置文本内容,HTML标签被转义
$("input").val(); //获取表单input内容
$("input").val("北风网"); //设置表单input内容
$("input").val(["男", "编程"]); //选定男,编程
2. 属性操作
$("#box").attr("id"); //获取id属性值
$("#box").attr("title", "www.ycku.com"); //设置属性
$("#box").attr({
"ttile": "www.ycku.com",
"color": "red"
}) //设置多个属性
$("#box").attr("title", function(index, value){
return "现在的title是" + value + ", " + "我是" + index + "号域名";
})
$("div").html(function(index, value) {
return value + "<em>www.li.com</em>"
})
$("#box").removeAttr("title"); //删除title属性
3. 样式操作
$("div").css("color"); //获取div color, 如果没有设置color style, 返回默认值
$("div").css("color", "red"); //设置color style.
var box = $("div").css(["color", "width", "height"]); //获取多个style
for(var key in box) {
console.log(key+":"+box[key]);
}
$.each(box, function(attr, value) {
console.log(attr+":"+value);
})
$("div").each(function(index, element) {
alert(index + element); //index 表示下标, element表示对应的原生dom对象
})
$("div").css({
"color": "red",
"background-color": black
}); //同时设置多个style
$("div").css("width", function(index, value){
console.log(index+":" + value); //value代表默认值
})
$("div").addClass("red bg"); //添加class
$("div").removeClass("red bg"); //删除class
$("div").toggleClass("red"); //toggle red类
$("div").toggleClass("red", true); //切换到带red类
$("div").toggleClass("red", false); //切换到不带red类
$("div").hasClass("red"); //判断是否包含red类
$("div").toggleClass(function(index, className, switchBool) {
if ($(this).hasClass("red")) {
$(this).removeClass("red');
return "green";
} else {
$(this).removeClass("green');
return "red";
}
})
4. 方法操作
$("div").width(); //边框宽度
$("div").innerWidth(); //边框宽度,包含padding
$("div").outerWidth(); //边框宽度,包含border
$("div").outerWidth(true); //边框宽度,包含margin
$("div").height(); //边框高度
$("div").innerHeight(); //边框高度,包含padding
$("div").outerHeight(); //边框高度,包含border
$("div").outerHeight(true); //边框高度,包含margin
5. 偏移操作
$("div").offset(); //相对于视口位置,返回object,包含left和right属性
$("div").position(); //相对于父元素位置
$("div").scrollTop(); //滚动条top位置
$("div").scrollLeft(); //滚动条left位置