1.介绍
JQ是JS写的一个插件库。
www.bootcdu.cn
2.引入
2.1 引入在线JQ
2.2 引入本地JQ
3.使用
$(function(){
alert(1);
});
执行函数
3.1 JQ获取元素
var $box = $("#box");
3.2更改页面内容
$box.html(“666”); 相当于innerHTML
$box.text(“666”); 相当于innerText
3.3 JS对象转为JQ对象
oBox ------$(oBox)
3.4 JQ对象转为JS对象
$li[1].innerHTML = “999”;
$li.get(2).innerHTML = “999”;
当JQ对象获取到多个时,选择其中一个使用eq()方法
3.4 each方法
遍历一个JQ对象,为每个匹配元素执行一个函数
$(“ul li”).each(function(i){
$(this).html(“我是第”+i+“个”);
});
3.5 attr()
设置/获取标签属性
var $box = $("#box");
$box.attr(“class”,“qq”)
会覆盖原有class属性,为 $box 添加class属性,值为qq
$box.removeAttr(“class”) 移除class属性
3.6 addClass()
$box.addClassr(“show”),不覆盖
$box.removeClass(“show”) 删除值为show的class属性
$box.removeClass() 删除所有class属性
3.7 toggleClass()方法
$(“li”).toggleClass(“show”);
取反,有的取消,没的添加
3.8 val()方法
value
在JQ里设置某个对象时,一般自带遍历
获取时,一般获取第一个
$("#box").width() 只获取数值,单位默认px
$("#box").height()
$("#box").innerWidth() width+padding
$("#box").innerHeight()
$("#box").outerWidth() width+padding+border
3.9 css属性修改
$("#box").css("width","200px")
修改多个
$("#box").css({
"width":"200px",
“height”:"100px"
});
3.10 定位
offset().left 到浏览器左边距离
offset().top 到浏览器顶部距离
position().top 到定位父级顶部距离
position().left 到定位父级左边距离
3.11 JQ事件
$("#box").click(function{
alert(1);
});
3.12 index()
对应下标,与$(this)配合使用
3.13 on绑定事件
$(“ul li”).on(“click”,function(){
alert( $(this).index());
});
绑定单个事件
$(“ul li”).on({
“click”:function(){
alert( $(this).index());
},
“monseenter”:function(){
console.log(“monseenter”);
},
});
off解绑事件,传参移除指定,不传参移除所有
3.14 hover事件
$("#box").hover(functiion(){
console.log(“haha”),
console.log(“hehe”);
});
传一个函数时,移入移出各执行一次
传两个函数时,移入执行第一个函数,移出执行第二个函数
第二个函数可以传空函数
3.15 动画
show/hide/toggle
fadeTo
fadeOut 淡出
fadeIn 淡入
slideUp 向上划出
slideDown 向下划入
这三组可以接受数字参数
也可以接受string代表运动曲线和function回调函数
animate()渐变,
$("div").click(function () {
$(this).animate({
"width":"200px",
"height":"300px"
});
})
stop清除动画队列
$("#box").stop(true,false).animate(…)
delay(时间)
延迟触发,只对动画有效
queue()
可以使不是动画的延迟触发
将function传入queue()中
3.16 scroll
滚动条位置
$(document).scrollTop() 读
$(document).scrollLeft() 读
设置
$(document).scrollLeft(1000)
3.17 添加标签
$("div").append(" <em> 小弟</em>")
在div中的最后面添加子标签
$("div").prepend(" <em> 大哥</em>")
在div中的最前面添加子标签
$(“div”).prepend( $(“b”))
将 $(“b”)移动到 $(“div”)子元素最前面
before() /after() 添加兄弟标签
3.18查找
hasClass() 返回true/false
childern() 找子代
find() 找后代
parent() 找父级
parents() 找上代直到html
siblings()找兄弟 不传参找所有,包括自己