21-jQuery操作CSS样式的方法
<script>
$(function () {
// 编写jQuery相关代码
// 1.逐个设置
$("div").css("width", "100px");
$("div").css("height", "100px");
$("div").css("background", "red");
// 2.链式设置
// 注意点: 链式操作如果大于3步, 建议分开
$("div").css("width", "100px").css("height", "100px").css("background", "blue");
// 3.批量设置
$("div").css({
width: "100px",
height: "100px",
background: "red"
});
// 4.获取CSS样式值
console.log($("div").css("background"));;
});
</script>
22-jQuery位置和尺寸操作的方法
<script>
$(function () {
// 编写jQuery相关代码
var btns = document.getElementsByTagName("button");
// 监听获取
btns[0].onclick = function () {
// 获取元素的宽度
// console.log($(".father").width());
// offset([coordinates])
// 作用: 获取元素距离窗口的偏移位
// console.log($(".son").offset().left);
// position()
// 作用: 获取元素距离定位元素的偏移位
console.log($(".son").position().left);
}
// 监听设置
btns[1].onclick = function () {
// 设置元素的宽度
// $(".father").width("500px")
$(".son").offset({
left: 10
});
// 注意点: position方法只能获取不能设置
// $(".son").position({
// left: 10
// });
// $(".son").css({
// left: "10px"
// });
}
});
</script>
23-jQuery的scrollTop方法
<script>
$(function () {
// 编写jQuery相关代码
var btns = document.getElementsByTagName("button");
// 监听获取
btns[0].onclick = function () {
// 获取滚动的偏移位
// console.log($(".scroll").scrollTop());
// 获取网页滚动的偏移位
// 注意点: 为了保证浏览器的兼容, 获取网页滚动的偏移位需要按照如下写法
console.log($("body").scrollTop()+$("html").scrollTop());
}
btns[1].onclick = function () {
// 设置滚动的偏移位
$(".scroll").scrollTop(300);
// 设置网页滚动偏移位
// 注意点: 为了保证浏览器的兼容, 设置网页滚动偏移位的时候必须按照如下写法
$("html,body").scrollTop(300);
}
});
</script>
24-jQuery事件绑定
<script>
$(function () {
// 编写jQuery相关代码
/*
jQuery中有两种绑定事件方式
1.eventName(fn);
编码效率略高/ 部分事件jQuery没有实现,所以不能添加
2.on(eventName, fn);
编码效率略低/ 所有js事件都可以添加
注意点:
可以添加多个相同或者不同类型的事件,不会覆盖
*/
// $("button").click(function () {
// alert("hello lnj");
// });
// $("button").click(function () {
// alert("hello 123");
// });
// $("button").mouseleave(function () {
// alert("hello mouseleave");
// });
// $("button").mouseenter(function () {
// alert("hello mouseenter");
// });
$("button").on("click", function () {
alert("hello click1");
});
$("button").on("click", function () {
alert("hello click2");
});
$("button").on("mouseleave", function () {
alert("hello mouseleave");
});
$("button").on("mouseenter", function () {
alert("hello mouseenter");
});
});
</script>
25-jQuery事件移除
<script>
$(function () {
function test1() {
alert("hello lnj");
}
function test2() {
alert("hello 123");
}
// 编写jQuery相关代码
$("button").click(test1);
$("button").click(test2);
$("button").mouseleave(function () {
alert("hello mouseleave");
});
$("button").mouseenter(function () {
alert("hello mouseenter");
});
// off方法如果不传递参数, 会移除所有的事件
// $("button").off();
// off方法如果传递一个参数, 会移除所有指定类型的事件
// $("button").off("click");
// off方法如果传递两个参数, 会移除所有指定类型的指定事件
$("button").off("click", test1);
});
</script>