day10-jQuery进阶语法

来源:互联网 发布:mac outlook windows 编辑:程序博客网 时间:2024/06/05 18:53

1、链式调用(连续调用)

1.1 解读懂下面的案例

$(".box1").css({backgroundColor:"red"}).fadeOut(1000).next().css({fontSize:"30px"}).slideUp(1000);

解读:找到class=“.box1”的元素.修改css属性的backgroundColor属性.然后在1000毫秒内淡出。然后找到下一个元素.修改css属性的fontSize属性。然后在1000毫秒内卷出。完毕!
1.2 层级菜单案例

$(".level1").click(function () {  // 取出所有第一级a标签 设置点击事件    $(this).next().slideDown().parent().siblings().children("ul").slideUp();});

2、jQuery中的动画效果

参1 要改变的属性, 参2 动画的时间,参3 动画的曲线swing/linear,参4 动画结束执行时回调函数

$(".box").animate({width:200,height:250},2000,'swing',function () {    alert("我完了");});

注意:jQuery中的动画效果是不支持颜色的,支持颜色下载jquery.animate-colors-min.js后导入就可以用了。

3、jQuery中获取元素宽、高、位置的方法

$(".box1").width(); // 通过方法获取元素的width属性 $(".box1").height();
$(".box1”).innerWidth(); // 获取的是width+padding的宽度,$(".box1”).innerHeight();
$(".box1”).outerWidth(); // width包含padding和border的宽高 $(".box1”).outerHeight();
$(".box1”).outerWidth(true); // width+padding+border+margin, $(".box1”).outerHeight(true);
var offset = $(".box1").offset(); // 获取标签的位置对象,offset对象有两个属性,left, top;

4、浏览器宽高

$(window).width(); // 浏览器宽
$(window).height(); // 浏览器高
$(document).width(); // 文档宽
$(document).height(); // 文档高
区别: 当文档内容的宽高不超出浏览器的宽高 这是就和浏览器可视区域宽高一样,如果超过 就是自己内容真实宽高

5、滚动的距离和滚动监听

var scrollLeft = $(document).scrollLeft(); // document换成window也是一样的
var scrollTop = $(document).scrollTop(); // 上下滚动的距离
$(window).scroll(function () { … }); // 监听页面的滚动

6、加入购物车的小红点动画关键代码

$red.css({ left: startLeft, top: startTop }).show(); // 显示小圆点
$red.stop().animate({ left: endLeft, top: endTop }, function () {}); // 小圆点移动的动画

7、“固定菜单”的关键代码

$(window).scroll(function () {}); // 监听滚动条滑动
var scrollTop = $(document).scrollTop(); // 获取滑动的距离
if (scrollTop > 150) { … } //判断滑动的距离 如果超过蓝色区域高度
$menu.css({ position: "fixed", left: "50%", top: 0, marginLeft: "-500px" });// 如果超过蓝色区域高度 把菜单固定定位
$remenu.show(); // 需要有一个占着位置,不然后面的内容会顶上来的
$menu.css({ position: "static", left: "50%", top: 0, marginLeft: "auto" });// 还原原来的设置
$remenu.hide(); //menu显示了之后,remenu就隐藏
// 点击返回顶部

$(".back").click(function () {    $("body,html").animate({scrollTop:0});  // body,html都写是为了兼容浏览器  scrollTop不是样式 是对象里的一个属性});

8、jQuery操作标签内容

$(".box").html("<a href=''>哈哈哈</a>”); // 相当于js里的innerHtml
$(".box").text("<a href=''>哈哈哈</a>”); // 相当于js里的innerText

9、操作元素属性

var href = $(".a1").prop("href”); // 获取系统属性
$(".a1").prop({ "href": "http://www.baidu.com", "target": "_blank" }); // 设置系统属性
var mydate1 = $(".a1").attr("mydate”); // 可以获取自定义属性,也可以获取系统属性
prop和attr的区别:如果是自己本身的属性用 prop,如果是自定义的就用 attr,在input的checkbox中的checked值时会有体现,本值和false的区别。

10、jQuery中获取的属性的方法

$("#talkwords").val(); //value
$("#words").html(); // innerHtml

11、自带的循环

$(".list li").each(function (index) {  // 当前循环到的li    // console.log(arguments);    $(this).html(index + 1);});
var aList = [10,8,2,4,6,3,2,7];$.each(aList,function (index) {  // 参1 要循环的集合 参2循环的方法    console.log(aList[index]);});