目录
一、简介
定义:
jQuery 是一个 JavaScript 库。
jQuery 极大地简化了 JavaScript 编程。
jQuery 很容易学习。
jQuery库包含以下功能:
- HTML 元素选取
- HTML 元素操作
- CSS 操作
- HTML 事件函数
- JavaScript 特效和动画
- HTML DOM 遍历和修改
- AJAX
- Utilities
提示: 除此之外,Jquery还提供了大量的插件。
书写规则:
支持链式操作;
在变量前加"$"符号(var $variable = jQuery 对象);
注:此规定并不是强制要求。
二、安装
网页中添加 jQuery
可以通过多种方法在网页中添加jQuery。 你可以使用以下方法:
- 从 jQuery.com 下载 jQuery库
- 从 CDN 中载入 jQuery, 如从Google中加载jQuery
下载 jQuery
有两个版本的 jQuery 可供下载:
- Production version - 用于实际的网站中,已被精简和压缩。
- Development version - 用于测试和开发(未压缩,是可读的代码)
以上两个版本都可以从 jQuery.com 中下载。
jQuery 库是一个 JavaScript 文件,您可以使用 HTML 的 <script> 标签引用它:
<head>
<script src="jquery-3.3.1.js"></script>
</head>
提示: 将下载的文件放在网页的同一目录下,就可以使用jQuery。
您是否很疑惑为什么我们没有在 <script> 标签中使用 type="text/javascript" ? 在 HTML5 中,不必那样做了。JavaScript 是 HTML5 以及所有现代浏览器中的默认脚本语言! |
三、查找元素
1、选择器
1.1 基本选择器 $("*") $("#id") $(".class") $("element") $(".class,p,div")
1.2层级选择器 $(".outer div")(所有的后代) $(".outer>div")(所有的子代) $(".outer+div")(匹配所有跟在.outer后面的div)
$(".outer~div")(.outer后面的所有div)
1.3 基本筛选器 $("li:first") $("li:eq(2)") $("li:even")(偶数) $("li:gt(1)")
$('li:first') //第一个元素
$('li:last') //最后一个元素
$("tr:even") //索引为偶数的元素,从 0 开始
$("tr:odd") //索引为奇数的元素,从 0 开始
$("tr:eq(1)") //给定索引值的元素
$("tr:gt(0)") //大于给定索引值的元素
$("tr:lt(2)") //小于给定索引值的元素
$(":focus") //当前获取焦点的元素
$(":animated") //正在执行动画效果的元素
1.4 属性选择器 $('[id="div1"]') $('["alex="sb"][id]')
1.5 表单选择器 $("[type='text']") 简写成 $(":text") 注意只适用于input标签
$(":input") //匹配所有 input, textarea, select 和 button 元素
$(":text") //所有的单行文本框
$(":password") //所有密码框
$(":radio") //所有单选按钮
$(":checkbox") //所有复选框
$(":submit") //所有提交按钮
$(":reset") //所有重置按钮
$(":button") //所有button按钮
$(":file") //所有文件域
$("input:checked") //所有选中的元素
$("select option:selected") //select中所有选中的option元素
2 筛选器
2.1 过滤筛选器
$("li").eq(2) $("li").first() $("ul li").hasclass("test") (检测li中的是否含有某个特定的类,有的话返回true)
$("p").eq(0) //当前操作中第N个jQuery对象,类似索引
$('li').first() //第一个元素
$('li').last() //最后一个元素
$(this).hasClass("test") //元素是否含有某个特定的类,返回布尔值
$('li').has('ul') //包含特定后代的元素
2.2 查找筛选器
$("div").children(".test")(只考虑子元素,而不考虑所有的后代) $("div").find(".test") (考虑所有的后代)
$(".test").next() $(".test").nextAll() $(".test").nextUntil() (开区间)
$("div").prev() $("div").prevAll() $("div").prevUntil()
$(".test").parent() $(".test").parents()(祖先元素集合) $(".test").parentUntil()
$("div").siblings() (所有的同辈元素不包括自己)
$("div").children() //div中的每个子元素,第一层
$("div").find("span") //div中的包含的所有span元素,子子孙孙
$("p").next() //紧邻p元素后的一个同辈元素
$("p").nextAll() //p元素之后所有的同辈元素
$("#test").nextUntil("#test2") //id为"#test"元素之后到id为'#test2'之间所有的同辈元素,掐头去尾
$("p").prev() //紧邻p元素前的一个同辈元素
$("p").prevAll() //p元素之前所有的同辈元素
$("#test").prevUntil("#test2") //id为"#test"元素之前到id为'#test2'之间所有的同辈元素,开区间
$("p").parent() //每个p元素的父元素
$("p").parents() //每个p元素的所有祖先元素,body,html
$("#test").parentsUntil("#test2") //id为"#test"元素到id为'#test2'之间所有的父级元素,掐头去尾
$("div").siblings() //所有的兄弟元素,不包括自己
四、属性操作
1、基本属性操作
$("img").attr("src"); //返回文档中所有图像的src属性值
$("img").attr("src","test.jpg"); //设置所有图像的src属性
$("img").removeAttr("src"); //将文档中图像的src属性删除
$("input[type='checkbox']").prop("checked", true); //选中复选框
$("input[type='checkbox']").prop("checked", false);
$("img").removeProp("src"); //删除img的src属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="div1" con="c1"></div>
<input type="checkbox" checked="checked">是否可见
<input type="checkbox">是否可见
<input type="text" value="123">
<div value="456"></div>
<div id="id1">
uuuuu
<p>ppppp</p>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
// console.log($("div").hasClass("div11")); //false
// console.log($("div").attr("con"))//c1
// console.log($("div").attr("con","c2"))
// console.log($(":checkbox:first").attr("checked"))
// console.log($(":checkbox:last").attr("checked"))
//
// console.log($(":checkbox:first").prop("checked"))
// console.log($(":checkbox:last").prop("checked"))
// console.log($("div").prop("con"))
// console.log($("div").prop("class"))
// console.log($("#id1").html());
// console.log($("#id1").text());
//console.log($("#id1").html("<h1>YUAN</h1>"))
//console.log($("#id1").text("<h1>YUAN</h1>"))
//固有属性
// console.log($(":text").val());
// console.log($(":text").next().val())
// $(":text").val("789");
$("div").css({"color":"red","background-color":"green"})
</script>
</body>
</html>
2、CSS类
$("p").addClass("selected"); //为p元素加上 'selected' 类
$("p").removeClass("selected"); //从p元素中删除 'selected' 类
$("p").toggleClass("selected"); //如果存在就删除,否则就添加
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.back{
background-color: rebeccapurple;
height: 2000px;
}
.shade{
position: fixed;
top: 0;
bottom: 0;
left:0;
right: 0;
background-color: coral;
opacity: 0.4;
}
.hide{
display: none;
}
.models{
position: fixed;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
height: 200px;
width: 200px;
background-color: gold;
}
</style>
</head>
<body>
<div class="back">
<input id="ID1" type="button" value="click" onclick="action1(this)">
</div>
<div class="shade hide"></div>
<div class="models hide">
<input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>
<script src="jquery-3.1.1.js"></script>
<script>
function action2(self) {
$(self).parent().addClass("hide").prev().addClass("hide"); //紧邻p元素前的一个兄弟元素
// $(self).parent().prev().addClass("hide")
// $(self).parent().parent().children(".models,.shade").addClass("hide")
}
function action1(self){
$(self).parent().siblings().removeClass("hide");
}
// function action2(self){
// $(self).parent().parent().children(".models,.shade").addClass("hide")
//
// }
</script>
</body>
</html>
3、HTML代码/文本/值
$('p').html(); //返回p元素的html内容
$("p").html("Hello <b>Aaron</b>!"); //设置p元素的html内容
$('p').text(); //返回p元素的文本内容
$("p").text("Aaron"); //设置p元素的文本内容
$("input").val(); //获取文本框中的值
$("input").val("Aaron"); //设置文本框中的内容
五、CSS操作
1、样式
$("p").css("color"); //访问查看p元素的color属性
$("p").css("color","red"); //设置p元素的color属性为red
$("p").css({ "color": "red", "background": "yellow" }); //设置p元素的color为red,background属性为yellow(设置多个属性要用{}字典形式)
2、位置
$('p').offset() //元素在当前视口的相对偏移,Object {top: 122, left: 260}
$('p').offset().top
$('p').offset().left
$("p").position() //元素相对父元素的偏移,对可见元素有效,Object {top: 117, left: 250}
$(window).scrollTop() //获取滚轮滑的高度
$(window).scrollLeft() //获取滚轮滑的宽度
$(window).scrollTop('100') //设置滚轮滑的高度为10
3、尺寸
$("p").height(); //获取p元素的高度
$("p").width(); //获取p元素的宽度
$("p:first").innerHeight() //获取第一个匹配元素内部区域高度(包括补白、不包括边框)
$("p:first").innerWidth() //获取第一个匹配元素内部区域宽度(包括补白、不包括边框)
$("p:first").outerHeight() //匹配元素外部高度(默认包括补白和边框)
$("p:first").outerWidth() //匹配元素外部宽度(默认包括补白和边框)
$("p:first").outerHeight(true) //为true时包括边距
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.div1,.div2{
width: 200px;
height: 100px;
}
.div1{
border: 5px solid rebeccapurple;
padding: 20px;
margin: 2px;
background-color: antiquewhite;
}
.div2{
background-color: rebeccapurple;
}
/*.outer{*/
/*position: relative;*/
/*}*/
</style>
</head>
<body>
<div class="div1"></div>
<div class="outer">
<div class="div2"></div>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
// offset()相对于视口的偏移量
console.log($(".div1").offset().top);//2
console.log($(".div1").offset().left);//2
//
console.log($(".div2").offset().top);//154
console.log($(".div2").offset().left);//0
//position():相对于已经定位的父标签的偏移量
console.log($(".div1").position().top);
console.log($(".div1").position().left);
console.log($(".div2").position().top);
console.log($(".div2").position().left);
console.log($(".div1").height("300px"));
console.log($(".div1").innerHeight());
console.log($(".div1").outerHeight());
console.log($(".div1").outerHeight(true));//354
</script>
</body>
</html>
六、文档处理
1、内部插入
$("p").append("<b>Aaron</b>"); //每个p元素内后面追加内容
$("p").appendTo("div"); //p元素追加到div内后
$("p").prepend("<b>Hello</b>"); //每个p元素内前面追加内容
$("p").prependTo("div"); //p元素追加到div内前
2、外部插入
$("p").after("<b>Aaron</b>"); //每个p元素同级之后插入内容
$("p").before("<b>Aaron</b>"); //在每个p元素同级之前插入内容
$("p").insertAfter("#test"); //所有p元素插入到id为test元素的后面
$("p").insertBefore("#test"); //所有p元素插入到id为test元素的前面
3、替换
$("p").replaceWith("<b>Paragraph. </b>"); //将所有匹配的元素替换成指定的HTML或DOM元素
$("<b>Paragraph. </b>").replaceAll("p"); //用匹配的元素替换掉所有 selector匹配到的元素
4、删除
$("p").empty(); //删除匹配的元素集合中所有的子节点,不包括本身
$("p").remove(); //删除所有匹配的元素,包括本身
$("p").detach(); //删除所有匹配的元素(和remove()不同的是:所有绑定的事件、附加的数据会保留下来)
5、复制
$("p").clone() //克隆元素并选中克隆的副本
$("p").clone(true) //布尔值指事件处理函数是否会被复制
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="c1">
<p>PPP</p>
</div>
<button>add</button>
<script src="jquery-3.1.1.js"></script>
<script>
$("button").click(function () {
//$(".c1").append("<h1>HELLO YUAN</h1>")
var $ele=$("<h1></h1>");
$ele.html("HELLO WORLD!");
$ele.css("color","red");
//内部插入
$(".c1").append($ele);
//$ele.appendTo(".c1")
//$(".c1").prepend($ele);
//$ele.prependTo(".c1")
//外部插入
//$(".c1").after($ele)
//$ele.insertAfter(".c1")
//$(".c1").before($ele)
//$ele.insertBefore(".c1")
//替换
//$("p").replaceWith($ele)
//删除与清空
//$(".c1").empty()
//$(".c1").remove()
//clone
// var $ele2= $(".c1").clone();
// $(".c1").after($ele2)
})
</script>
</body>
</html>
七、事件
1、页面载入
当页面载入成功后再运行的函数事件
$(document).ready(function(){
do something...
});
//简写
$(function($) {
do something...
});
2、页面处理
//bind 为每个匹配元素绑定事件处理函数,绑定多个用{}。
$("p").bind("click", function(){
alert( $(this).text() );
});
$(menuF).bind({
"mouseover":function () {
$(menuS).parent().removeClass("hide");
},"mouseout":function () {
$(menuS).parent().addClass("hide");
}
});
$("p").one( "click", fun...) //one 绑定一个一次性的事件处理函数
$("p").unbind( "click" ) //解绑一个事件
3、页面委派
// 与bind 不同的是当时间发生时才去临时绑定。
$("p").delegate("click",function(){
do something...
});
$("p").undelegate(); //p元素删除由 delegate() 方法添加的所有事件
$("p").undelegate("click") //从p元素删除由 delegate() 方法添加的所有click事件
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.1.1.js"></script>
<script>
// 事件准备加载方式一
$(document).ready(function () {
// $("ul li").html(5);
// 事件准备加载方式二
$(function () {
$("ul li").html(5);
});
//事件绑定简单形式
// var eles=document.getElementsByTagName("li")
// eles.onclick=function () {
// alert(123)
// }
// $("ul li").click(function () {
// alert(6666)
// });
// $("ul li").bind("click",function () {
// alert(777)
// });
//事件委托
$('ul').on("click","li",function () {
alert(999);
});
$("button").click(function () {
var $ele=$("<li>");
var len=$("ul li").length;
$ele.html((len+1)*1111);
$("ul").append($ele)
});
// $("ul li").unbind("click")
});
</script>
</head>
<body>
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
<button>add</button>
</body>
</html>
4、事件
$("p").click(); //单击事件
$("p").dblclick(); //双击事件
$("input[type=text]").focus() //元素获得焦点时,触发 focus 事件
$("input[type=text]").blur() //元素失去焦点时,触发 blur事件
$("button").mousedown()//当按下鼠标时触发事件
$("button").mouseup() //元素上放松鼠标按钮时触发事件
$("p").mousemove() //当鼠标指针在指定的元素中移动时触发事件
$("p").mouseover() //当鼠标指针位于元素上方时触发事件
$("p").mouseout() //当鼠标指针从元素上移开时触发事件
$(window).keydown() //当键盘或按钮被按下时触发事件
$(window).keypress() //当键盘或按钮被按下时触发事件,每输入一个字符都触发一次
$("input").keyup() //当按钮被松开时触发事件
$(window).scroll() //当用户滚动时触发事件
$(window).resize() //当调整浏览器窗口的大小时触发事件
$("input[type='text']").change() //当元素的值发生改变时触发事件
$("input").select() //当input 元素中的文本被选择时触发事件
$("form").submit() //当提交表单时触发事件
$(window).unload() //用户离开页面时
实例:(拖动框)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.1.1.js"></script>
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 200px;
position: absolute;
}
.title{
background-color: black;
height: 50px;
width: 500px;
line-height: 50px;
text-align: center;
color: white;
}
.content{
width: 500px;
height: 150px;
background-color: antiquewhite;
}
</style>
<script>
$(function () {
$(".title").mouseover(function () {
$(this).css("cursor","pointer");
}).mousedown(function (e) {
var eve = e || window.event;
// 原始鼠标横纵坐标位置
var old_m_x=eve.clientX;
var old_m_y=eve.clientY;
// console.log(old_m_x);
// console.log(old_m_y);
var old_box_y=$(this).parent().offset().top ;
var old_box_x=$(this).parent().offset().left ;
$(this).bind("mousemove",function (eve) {
var new_m_x=eve.clientX;
var new_m_y=eve.clientY;
var m_x=new_m_x-old_m_x;
var m_y=new_m_y-old_m_y;
//$(".box").css({"top":old_box_y+m_y+"px","left":old_box_x+m_x+"px"})
var x = old_box_x + m_x;
var y = old_box_y + m_y;
$(this).parent().css('left',x+'px');
$(this).parent().css('top',y+'px');
})
})
}).mouseout(function(){
$(this).unbind('mousemove');
})
</script>
</head>
<body>
<div class="box">
<div class="title">标题</div>
<div class="content">内容</div>
</div>
</body>
</html>
5、(event object) 对象
所有的事件函数都可以传入event参数方便处理事件
$("p").click(function(event){
alert(event.type); //"click"
});
(evnet object)属性方法:
event.pageX //事件发生时,鼠标距离网页左上角的水平距离
event.pageY //事件发生时,鼠标距离网页左上角的垂直距离
event.type //事件的类型
event.which //按下了哪一个键
event.data //在事件对象上绑定数据,然后传入事件处理函数
event.target //事件针对的网页元素
event.preventDefault() //阻止事件的默认行为(比如点击链接,会自动打开新页面)
event.stopPropagation() //停止事件向上层元素冒泡
八、效果
1、基本
$("p").show() //显示隐藏的匹配元素
$("p").show("slow"); //参数表示速度,("slow","normal","fast"),也可为900毫秒
$("p").hide() //隐藏显示的元素
$("p").toggle(); //切换 显示/隐藏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.1.1.js"></script>
<title>Title</title>
</head>
<body>
<div>hello</div>
<button onclick="f1()">显示</button>
<button onclick="f2()">隐藏</button>
<button onclick="f3()">切换</button>
<script>
function f1() {
$("div").show(1000);
// $("div").show(1000,function () {
// //alert("show")
// })
}
function f2() {
$("div").hide(1000,function () {
// alert(1243)
})
}
function f3() {
$("div").toggle(1000)
}
</script>
</body>
</html>
2、滑动
$("p").slideDown("900"); //用900毫秒时间将段落滑下
$("p").slideUp("900"); //用900毫秒时间将段落滑上
$("p").slideToggle("900"); //用900毫秒时间将段落滑上,滑下
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$("#slideDown").click(function(){
$("#content").slideDown(1000);
});
$("#slideUp").click(function(){
$("#content").slideUp(1000);
});
$("#slideToggle").click(function(){
$("#content").slideToggle(1000);
})
});
</script>
<style>
#content{
text-align: center;
background-color: lightblue;
border:solid 1px red;
/*display: none;*/
padding: 50px;
}
</style>
</head>
<body>
<div id="slideDown">出现</div>
<div id="slideUp">隐藏</div>
<div id="slideToggle">toggle</div>
<div id="content">hello world</div>
</body>
</html>
3、淡入淡出
$("p").fadeIn("900"); //用900毫秒时间将段落淡入
$("p").fadeOut("900"); //用900毫秒时间将段落淡出
$("p").fadeToggle("900"); //用900毫秒时间将段落淡入,淡出
$("p").fadeTo("slow", 0.6); //用900毫秒时间将段落的透明度调整到0.6
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$("#in").click(function(){
$("#id1").fadeIn(2000);
});
$("#out").click(function(){
$("#id1").fadeOut(2000);
});
$("#toggle").click(function(){
$("#id1").fadeToggle(2000);
});
$("#fadeto").click(function(){
$("#id1").fadeTo(1000,1);
});
});
</script>
</head>
<body>
<button id="in">fadein</button>
<button id="out">fadeout</button>
<button id="toggle">fadetoggle</button>
<button id="fadeto">fadeto</button>
<div id="id1" style="width: 80px;height: 80px;background-color: blueviolet"></div>
</body>
</html>
九、对象访问
$.trim() //去除字符串两端的空格
$.each() //遍历一个数组或对象,for循环
$.inArray() //返回一个值在数组中的索引位置,不存在返回-1
$.grep() //返回数组中符合某种标准的元素
$.extend() //将多个对象,合并到第一个对象
$.makeArray() //将对象转化为数组
$.type() //判断对象的类别(函数对象、日期对象、数组对象、正则对象等等
$.isArray() //判断某个参数是否为数组
$.isEmptyObject() //判断某个对象是否为空(不含有任何属性)
$.isFunction() //判断某个参数是否为函数
$.isPlainObject() //判断某个参数是否为用"{}"或"new Object"建立的对象
$.support() //判断浏览器是否支持某个特性
模拟each()内部实现机制:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="jquery-3.1.1.js"></script>
<script>
li = [11,22,33];
$.each(li,function (k,v) {
console.log(this);
console.log(k,v);
if (k == 1){
return false;
}
})
</script>
<script>
function myEach(obj,func) {
for (var i=0;i<obj.length;i++){
var current = obj[i];
var ret = func(i,current);
if (ret == false){
break;
}
}
}
var li = [10,20,30];
myEach(li,function (k,v) {
console.log(k,v);
return false;
})
</script>
</body>
</html>
十、插件拓展机制
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.1.1.js"></script>
<title>Title</title>
</head>
<body>
<p>111</p>
<p>222</p>
<p>333</p>
<script>
// $.each(obj,function () {
//
// });
//
// $("").each(function () {
//
// })
$.extend({
Myprint:function () {
console.log("hello")
}
});
// $.Myprint();
$.fn.extend({
GetText:function () {
// for(var i=0;i<this.length;i++){
// console.log(this[i].innerHTML)
// }
$.each($(this),function (x,y) {
//console.log(y.innerHTML)
console.log($(y).html())
})
}
});
$("p").GetText()
</script>
</body>
</html>
$.extend({
min: function(a, b) { return a < b ? a : b; }, //三元运算
max: function(a, b) { return a > b ? a : b; }
});
$.min(2,3); //2
$.max(4,5); //5
十一、实例
1、返回顶部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.div2{
width: 100%;
height: 800px;
}
.div1{
width: 40%;
height: 150px;
background-color: antiquewhite;
overflow: auto;
}
.div2{
background-color: rebeccapurple;
}
.returnTop{
position: fixed;
right: 20px;
bottom: 20px;
width: 90px;
height: 50px;
background-color: gray;
color: white;
text-align: center;
line-height: 50px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="div1">
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
<h1>1111</h1>
</div>
<!--局部返回-->
<div class="div2">
<button onclick="returnTop()">return</button>
</div>
<!--全局的返回-->
<div class="returnTop hide" onclick="returnTop()">返回顶部</div>
<script src="jquery-3.1.1.js"></script>
<script>
//当用户滚动指定的元素时,会发生 scroll 事件。
//scroll 事件适用于所有可滚动的元素和 window 对象(浏览器窗口)。
//scroll() 方法触发 scroll 事件,或规定当发生 scroll 事件时运行的函数。
//对元素滚动的次数进行计数:
//$("div").scroll(function(){
//$("span").text(x+=1);
//});
window.onscroll=function () {
// console.log($(window).scrollTop());
if($(window).scrollTop()>300){
$(".returnTop").removeClass("hide")
}else {
$(".returnTop").addClass("hide")
}
};
function returnTop() {
$(window).scrollTop(0)
}
$(".div2 button").click(function () {
$(".div1").scrollTop(0)
})
</script>
</body>
</html>
2、正反选
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="selectall();">全选</button>
<button onclick="cancel();">取消</button>
<button onclick="reverse();">反选</button>
<hr>
<table border="1">
<tr>
<td><input type="checkbox"></td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>222</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>333</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>444</td>
</tr>
</table>
,
<script src="jquery-3.1.1.js"></script>
<script>
function selectall() {
$(":checkbox").each(function () {
$(this).prop("checked",true)
})
}
function cancel() {
$(":checkbox").each(function () {
$(this).prop("checked",false)
})
}
function reverse() {
$(":checkbox").each(function () {
if($(this).prop("checked")){
$(this).prop("checked",false)
}
else {
$(this).prop("checked",true)
}
})
}
</script>
</body>
</html>
3、左侧菜单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.menu{
height: 600px;
width: 30%;
background-color: #2F4F4F;
float: left;
}
.title{
line-height: 50px;
color: #ddd;
}
.title:hover{
cursor: pointer;
color: lightcyan;
font-size: 18px;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="outer">
<div class="menu">
<div class="item">
<div class="title" onclick="Show(this);">菜单一</div>
<div class="con">
<div>111</div>
<div>111</div>
<div>111</div>
</div>
</div>
<div class="item">
<div class="title" onclick="Show(this);">菜单二</div>
<div class="con hide">
<div>222</div>
<div>222</div>
<div>222</div>
</div>
</div>
<div class="item">
<div class="title" onclick="Show(this);">菜单三</div>
<div class="con hide">
<div>333</div>
<div>333</div>
<div>333</div>
</div>
</div>
</div>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
function Show(self) {
$(self).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");
}
</script>
</body>
</html>
4、菜单切换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.tab_outer{
margin: 0px auto;
width: 60%;
}
.menu{
background-color: #cccccc;
border: 1px solid #ccc;
line-height: 40px;
}
.menu li{
display: inline-block;
color: white;
}
.menu li:hover {
cursor: pointer;
}
.menu a{
padding: 11px;
}
.content{
border: 1px solid #ccc;
height: 300px;
font-size: 30px;
}
.hide{
display: none;
}
.current{
background-color: #0099dd;
color: black;
}
</style>
</head>
<body>
<div class="tab_outer">
<ul class="menu">
<li lis="c1" class="current" onclick="Tab(this);">菜单一</li>
<li lis="c2" onclick="Tab(this);">菜单二</li>
<li lis="c3" onclick="Tab(this);">菜单三</li>
</ul>
<div class="content">
<div id="c1">内容一</div>
<div id="c2" class="hide">内容二</div>
<div id="c3" class="hide">内容三</div>
</div>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
function Tab(self) {
$(self).addClass("current").siblings().removeClass("current");
var x = "#" + $(self).attr("lis");
$(x).removeClass("hide").siblings().addClass("hide");
}
</script>
</body>
</html>
5、添加与删除标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="outer">
<div class="item">
<button onclick="add(this)">+</button>
<input type="text">
</div>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
function add(self) {
//var $clone_obj=$(".item").clone();//会一起找到复制后的对象
var $clone_obj=$(self).parent().clone();//通过this得到的是当前的对象,是唯一的,当clone(true)不复制事件
$clone_obj.children("button").html("-").attr("onclick","remove_obj(this)");//通过attr绑定一个事件叫remove_obj
$(".outer").append($clone_obj)
}
function remove_obj(self) {
$(self).parent().remove()
}
</script>
</body>
</html>
6、编辑框
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.edit-mode{
background-color: #b3b3b3;
padding: 8px;
text-decoration: none;
color: white;
}
.editing{
background-color: #f0ad4e;
}
</style>
</head>
<body>
<div style="padding: 20px">
<input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
<input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
<input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />
<a id="edit_mode" class="edit-mode" href="javascript:void(0);" onclick="EditMode(this, '#tb1');">进入编辑模式</a>
</div>
<table border="1">
<thead>
<tr>
<th>选择</th>
<th>主机名</th>
<th>端口</th>
<th>状态</th>
</tr>
</thead>
<tbody id="tb1">
<tr>
<td><input type="checkbox" /></td>
<td edit="true">v1</td>
<td>v11</td>
<td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td edit="true">v1</td>
<td>v11</td>
<td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td edit="true">v1</td>
<td>v11</td>
<td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script>
/*
监听是否已经按下control键
*/
window.globalCtrlKeyPress = false;
window.onkeydown = function(event){
if(event && event.keyCode == 17){
window.globalCtrlKeyPress = true;
}
};
window.onkeyup = function(event){
if(event && event.keyCode == 17){
window.globalCtrlKeyPress = false;
}
};
/*
按下Control,联动表格中正在编辑的select
*/
function MultiSelect(ths){
if(window.globalCtrlKeyPress){
var index = $(ths).parent().index();
var value = $(ths).val();
$(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
$(this).parent().parent().children().eq(index).children().val(value);
});
}
}
</script>
<script type="text/javascript">
$(function(){
BindSingleCheck('#edit_mode', '#tb1');
});
function BindSingleCheck(mode, tb){
$(tb).find(':checkbox').bind('click', function(){
var $tr = $(this).parent().parent();
if($(mode).hasClass('editing')){
if($(this).prop('checked')){
RowIntoEdit($tr);
}else{
RowOutEdit($tr);
}
}
});
}
function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
var sel= document.createElement('select');
$.each(attrs,function(k,v){
$(sel).attr(k,v);
});
$.each(csses,function(k,v){
$(sel).css(k,v);
});
$.each(option_dict,function(k,v){
var opt1=document.createElement('option');
var sel_text = v[item_value];
var sel_value = v[item_key];
if(sel_value==current_val){
$(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
}else{
$(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
}
});
return sel;
}
STATUS = [
{'id': 1, 'value': "在线"},
{'id': 2, 'value': "下线"}
];
BUSINESS = [
{'id': 1, 'value': "车上会"},
{'id': 2, 'value': "二手车"}
];
function RowIntoEdit($tr){
$tr.children().each(function(){
if($(this).attr('edit') == "true"){
if($(this).attr('edit-type') == "select"){
var select_val = $(this).attr('sel-val');
var global_key = $(this).attr('global-key');
var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
$(this).html(selelct_tag);
}else{
var orgin_value = $(this).text();
var temp = "<input value='"+ orgin_value+"' />";
$(this).html(temp);
}
}
});
}
function RowOutEdit($tr){
$tr.children().each(function(){
if($(this).attr('edit') == "true"){
if($(this).attr('edit-type') == "select"){
var new_val = $(this).children(':first').val();
var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
$(this).attr('sel-val', new_val);
$(this).text(new_text);
}else{
var orgin_value = $(this).children().first().val();
$(this).text(orgin_value);
}
}
});
}
function CheckAll(mode, tb){
if($(mode).hasClass('editing')){
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
}else{
check_box.prop('checked',true);
RowIntoEdit(tr);
}
});
}else{
$(tb).find(':checkbox').prop('checked', true);
}
}
function CheckReverse(mode, tb){
if($(mode).hasClass('editing')){
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
check_box.prop('checked',false);
RowOutEdit(tr);
}else{
check_box.prop('checked',true);
RowIntoEdit(tr);
}
});
}else{
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
check_box.prop('checked',false);
}else{
check_box.prop('checked',true);
}
});
}
}
function CheckCancel(mode, tb){
if($(mode).hasClass('editing')){
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
check_box.prop('checked',false);
RowOutEdit(tr);
}else{
}
});
}else{
$(tb).find(':checkbox').prop('checked', false);
}
}
function EditMode(ths, tb){
if($(ths).hasClass('editing')){
$(ths).removeClass('editing');
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
RowOutEdit(tr);
}else{
}
});
}else{
$(ths).addClass('editing');
$(tb).children().each(function(){
var tr = $(this);
var check_box = tr.children().first().find(':checkbox');
if(check_box.prop('checked')){
RowIntoEdit(tr);
}else{
}
});
}
}
</script>
</body>
</html>
7、模态对话框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.shade{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,.6) ;
z-index: 20;
}
.modal{
position: fixed;
left: 50%;
top: 50%;
height: 300px;
width: 400px;
margin-top: -150px;
margin-left: -200px;
z-index: 30;
border: 1px solid #ddd;
background-color: white;
}
.hide{
display: none;
}
.modal form {
position: fixed;
left: 50%;
top: 50%;
height: 200px;
width: 229px;
border: 1px;
margin-left: -115px;
margin-top: -100px;
}
.modal form p {
float: right;
margin-top: 12px;
}
.modal form span {
float: right;
display: inline-block;
height: 18px;
width: 170px;
background-color: #FFEBEB;
text-align: center;
border: 1px solid #ffbdbe;
color: #e4393c;
font-size: 14px;
visibility: hidden;
}
.modal form [type="button"] {
position: absolute;
bottom: -30px;
left: 115px;
}
.modal form [value="提交"]{
left: 50px;
}
</style>
</head>
<body>
<div style="width: 300px; margin: 0 auto">
<input type="button" value="添加主机" onclick="return Add();" />
<table style="border: 2px solid #F5F5F5; width: 300px;">
<thead>
<tr>
<th >主机名</th>
<th >IP</th>
<th >端口</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td target="host">c1.com</td>
<td target="ip">1.1.1.1</td>
<td target="port">8888</td>
<td onclick="Edit(this);">Edit</td>
</tr>
<tr>
<td target="host">c2.com</td>
<td target="ip">1.1.1.1</td>
<td target="port">8888</td>
<td onclick="Edit(this);">Edit</td>
</tr>
<tr>
<td target="host">c3.com</td>
<td target="ip">1.1.1.1</td>
<td target="port">8888</td>
<td onclick="Edit(this);">Edit</td>
</tr>
<tr>
<td target="host">.com</td>
<td target="ip">1.1.1.1</td>
<td target="port">8888</td>
<td onclick="Edit(this);">Edit</td>
</tr>
</tbody>
</table>
</div>
<div class="shade hide"></div>
<div class="modal hide">
<form action="" method="get">
<p>主机名:<input type="text" id="host" name="host"><br><span></span></p>
<p>IP地址:<input type="text" id='ip' name="ip"><br><span></span></p>
<p>端口号:<input type="text" id='port' name="port"><br><span></span><br></p>
<input type="button" value="提交" onclick="return SubmitForm();">
<input type="button" value="取消" onclick="HideModal();">
</form>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
$(function () {
$("tr:even").css("background-color","#f5f5f5");
});
function Edit(ths) {
$(".shade,.modal").removeClass("hide");
prevList = $(ths).prevAll();
prevList.each(function () {
var text = $(this).text();
var target = $(this).attr("target");
$("#"+target).val(text);
});
}
function HideModal() {
$(".shade,.modal").addClass("hide");
$(".modal").find("input[type='text']").val("");
Addd = false;
}
function SubmitForm() {
var flag = Detection();
try {
if (Addd && flag){
$("tbody").append($("tr").last().clone());
$(".modal").find("input[type='text']").each(function () {
var value = $(this).val();
var name = $(this).attr("name");
($("tr").last().children()).each(function () {
if ($(this).attr("target") == name){
$(this).text(value);
return
}
}
)});
Addd = false;
HideModal();
return false;
}
}catch (e){}
if (flag){
$(".modal").find("input[type='text']").each(function () {
var value = $(this).val();
var name = $(this).attr("name");
$(prevList).each(function () {
if ($(this).attr("target") == name){
$(this).text(value);
return
}
}
)});
$(".modal,.shade").addClass("hide");
HideModal();
}
return flag;
}
function Detection() {
var flag = true;
$(".modal").find("input[type='text']").each(function () {
var value = $(this).val();
if (value.length == 0){
$(this).next().next().css("visibility","visible").text("亲,不能为空");
flag = false;
return false;
}else {
$(this).next().next().css("visibility","hidden").text("");
}
if ($(this).attr('name') == "host"){
var r = /(\.com)$/;
if (r.test(value) == false){
$(this).next().next().css("visibility","visible").text("主机名必须以.com结尾");
flag = false;
return false;
}
}else if ($(this).attr('name') == "ip"){
var r2 = /^(([0-2]?[0-9][0-9]?)\.){3}([0-2]?[0-9][0-9]?)$/;
if (r2.test(value) == false){
$(this).next().next().css("visibility","visible").text("ip 地址格式有误");
flag = false;
return false;
}
}else if ($(this).attr('name') == "port"){
var r3 = /^([0-9]{1,5})$/;
if ((r3.test(value) == false) || (value > 65535)){
$(this).next().next().css("visibility","visible").text("端口必须为0-65535");
flag = false;
return false;
}
}else {
$(this).next().next().css("visibility","hidden").text("");
}
});
return flag;
}
function Add() {
Addd = true;
$(".shade,.modal").removeClass("hide");
}
</script>
</body>
</html>
8、商城商品放大镜
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
<meta http-equiv="X-UA-Compatible" content="IE=8">
<title>购物商城</title>
<style>
*{
margin: 0;
padding: 0;
}
.outer{
position:relative;
width:350px;
height:350px;
border:1px solid black;
}
.outer .small-box{
position: relative;
z-index: 1;
}
.outer .small-box .mark{
position: absolute;
display: block;
width: 350px;
height: 350px;
background-color: #fff;
filter: alpha(opacity=0);
opacity: 0;
z-index: 10;
}
.outer .small-box .float-box{
display: none;
width: 175px;
height: 175px;
position: absolute;
background: #DAEEFC;
filter: alpha(opacity=40);
opacity: 0.4;
}
.outer .big-box{
position: absolute;
top: 0;
left: 351px;
width: 350px;
height: 350px;
overflow: hidden;
border: 1px solid transparent;
z-index: 1;
}
.outer .big-box img{
position: absolute;
z-index: 5
}
</style>
</head>
<body>
<div class="outer">
<div class="small-box">
<div class="mark"></div>
<div class="float-box" ></div>
<img width="350" height="350" src="1.jpg">
</div>
<div class="big-box">
<img width="900px" height="900px" src="1.jpg" >
</div>
</div>
<script src="jquery-3.1.1.js"></script>
<script>
$(function(){
$(".mark").mouseover(function () {
$(".float-box").css("display","block");
$(".big-box").css("display","block");
});
$(".mark").mouseout(function () {
$(".float-box").css("display","none");
$(".big-box").css("display","none");
});
$(".mark").mousemove(function (e) {
var _event = e || window.event; //兼容多个浏览器的event参数模式
var float_box_width = $(".float-box")[0].offsetWidth;
var float_box_height = $(".float-box")[0].offsetHeight;//175,175
var float_box_width_half = float_box_width / 2;
var float_box_height_half = float_box_height/ 2;//87.5,87.5
var small_box_width = $(".outer")[0].offsetWidth;
var small_box_height = $(".outer")[0].offsetHeight;//360,360
var mouse_left = _event.clientX - float_box_width_half;
var mouse_top = _event.clientY - float_box_height_half;
if (mouse_left < 0) {
mouse_left = 0;
} else if (mouse_left > small_box_width - float_box_width) {
mouse_left = small_box_width - float_box_width;
}
if (mouse_top < 0) {
mouse_top = 0;
} else if (mouse_top > small_box_height - float_box_height) {
mouse_top = small_box_height - float_box_height;
}
$(".float-box").css("left",mouse_left + "px");
$(".float-box").css("top",mouse_top + "px");
var percentX = ($(".big-box img")[0].offsetWidth - $(".big-box")[0].offsetWidth) / (small_box_width - float_box_width);
var percentY = ($(".big-box img")[0].offsetHeight - $(".big-box")[0].offsetHeight) / (small_box_height - float_box_height);
console.log($(".big-box img")[0].offsetWidth,$(".big-box")[0].offsetWidth,small_box_width,float_box_width)
console.log(percentX,percentY)
$(".big-box img").css("left",-percentX * mouse_left + "px");
$(".big-box img").css("top",-percentY * mouse_top + "px")
})
})
</script>
</body>
</html>
综合项目:轮播图