博客列表 >JQuery appendTo() prependTo() insertAfter() insertBefore()—2018年4月9日10时26分

JQuery appendTo() prependTo() insertAfter() insertBefore()—2018年4月9日10时26分

Gee的博客
Gee的博客原创
2018年04月09日 10:34:36528浏览

appendTo() prependTo() insertAfter() insertBefore()

将节点添加或移动到目标节点的操作

汉诺塔小动画:

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>homeword</title>
	<style type="text/css">
		.box {
			width: 600px;
			height: 300px;
			border: 1px solid #888;
		}

		.line1 {
			width: 200px;
			height: 300px;
			background-color: skyblue;
			display: table-cell;
			vertical-align: bottom;
		}
		.line2 {
			width: 200px;
			height: 300px;
			background-color: gray;
			display: table-cell;
			vertical-align: bottom;
		}
		.line3 {
			width: 200px;
			height: 300px;
			background-color: lightgreen;
			display: table-cell;
			vertical-align: bottom;
		}
		
		.small {
			margin: 0 auto;
			width: 50px;
			height: 30px;
			border: 1px solid #999;
			background-color: wheat;
		}

		.medium {
			margin: 0 auto;
			width: 100px;
			height: 30px;
			border: 1px solid #999;
			background-color: wheat;
		}

		.large {
			margin: 0 auto;
			width: 150px;
			height: 30px;
			border: 1px solid #999;
			background-color: wheat;
		}
	</style>
</head>
<body>
	<div class="box">
		<div class="line1">
		</div>

		<div class="line2">
		</div>

		<div class="line3">
		</div>
	</div>
</body>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
	// 生成色块
	setTimeout(function(){
		$('<p>').addClass('small').appendTo($('.line1'))
	},1000)
	setTimeout(function(){
		$('<p>').addClass('medium').insertAfter($('p'))
	},1500)
	setTimeout(function(){
		$('<p>').addClass('large').insertAfter($('p:last'))
	},2000)
	// 移动色块
	// 最小色块移动到最右边
	setTimeout(function(){
		$('p:first').prependTo($('.line3'))
	},2500)
	// 中号色块移动到中间
	setTimeout(function(){
		$('p').eq(0).appendTo($('.line2'))
	},3000)
	// 最小色块移动到中间
	setTimeout(function(){
		$('p:last').prependTo($('.line2'))
	},3500)
	// 最大色块移动到最右边
	setTimeout(function(){
		$('p:eq(0)').appendTo($('.line3'))
	},4000)
	// 最小色块移动到最左边
	setTimeout(function(){
		$('p:eq(0)').appendTo($('.line1'))
	},4500)
	// 中号色块移动到最右边
	setTimeout(function(){
		$('p').eq(1).insertBefore($('p').eq(2))
	},5000)
	// 最小色块移动到最右边
	setTimeout(function(){
		$('p').eq(0).prependTo($('.line3'))
	},5500)
</script>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

效果图:

搜狗截图20180409102846.png

总结:

1.appendTo()

    语法:content.appendTo(target)

    参数:目标

    功能:插入到目标元素内容的后面

2.prependTo()

    语法:content.prependTo(target)

    参数:目标

    功能:插入到目标元素内容的前面

3.insertAfter()

    语法:content.insertAfter(target)

    参数:目标

    功能:插入到目标元素的后面

4.insertBefore()

    语法:content.insertBefore(target)

    参数:目标

    功能:插入到目标元素的前面

注意:appendTo()和prependTo()是目标元素内容前后

          insertAfter()和insertBefore()是目标元素前后

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议