jQuery动画效果
jQuery中提供了很多函数帮开发者实现一些动态效果,这里只介绍一些简单的操作,参考下面示例。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div{
background-color: antiquewhite;
width: 100px;
height: 100px;
}
</style>
<script src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function () {
//显示
$("#showBtn").click(function () {
//使用2秒的时间来显示
$("#myDiv").show(2000);
});
$("#hideBtn").click(function () {
//使用2秒的时间隐藏
$("#myDiv").hide(2000);
});
$("#fadeInBtn").click(function () {
//使用2秒的逐渐显示
$("#myDiv").fadeIn(2000);
});
$("#fadeOutBtn").click(function () {
//使用2秒的时间逐渐隐藏
$("#myDiv").fadeOut(2000);
});
//移动到指定位置
$("#animateBtn").click(function () {
$("#myDiv").animate({"margin-left":300});
$("#myDiv").animate({"margin-top":300});
});
});
</script>
</head>
<body>
<button id="showBtn">显示</button>
<button id="hideBtn">隐藏</button>
<br>
<button id="fadeInBtn">渐显</button>
<button id="fadeOutBtn">渐淡</button>
<br>
<button id="animateBtn">移动到指定位置</button>
<br>
<div id="myDiv"></div>
</body>
</html>
jQuery中的遍历
待遍历的html
<ul id="city">
<li>北京</li>
<li>上海</li>
<li>天津</li>
<li>广州</li>
</ul>
1.for循环
jquery对象本身就是一个数组对象,因此我们可以使用for直接遍历
$(function () {
//获取所有的ul下的li
let cities = $("#city li");
//遍历li
for (let i = 0; i < cities.length; i++) {
//获取内容
console.log(i+":"+cities[i].innerHTML);
}
});
2.jquery对象.each(匿名函数)
语法,在each方法中的参数是一个匿名函数:
jquery对象.each(function(index,element){});
* index:元素在集合中的索引
* element:集合中的每一个元素对象
匿名函数返回值:
* true:如果当前function返回为false,则结束循环(break)。
* false:如果当前function返回为true,则结束本次循环,继续下次循环(continue)
代码:
$(function () {
let cities = $("#city li");
cities.each(function (index,element) {
if("北京" == $(element).html()){
//如果当前function返回为false,则结束循环(break)。
//如果返回为true,则结束本次循环,继续下次循环(continue)
return true;
}
console.log(index+":"+$(element).html());
});
});
3.for..of: jquery 3.0 版本之后提供的方式
这个有点像java中的增强for循环
for(元素对象 of 容器对象)
代码:
$(function () {
let cities = $("#city li");
for(li of cities){
console.log($(li).html());
}
});