jQuery实现元素的插入
效果图:
图(1) 初始效果
图(2) 点击' 插入到此元素前面 '效果
代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> .div{ width: 200px; height: 200px; border: 1px solid #008080; background-color: #0095FF; text-align: center; line-height: 200px; color: white; font-size: 25px; float: left; } #num{ height: 30px; text-align: center; font-size: 16px; } #main{ width: 100%; height: 400px; margin-top: 20px; } button{ height: 35px; } .newDiv{ width: 200px; height: 200px; border: 1px solid #008080; background-color: #009999; text-align: center; line-height: 200px; color: white; font-size: 25px; float: left; } </style> <body> 插入到第几个元素:<input id="num" type="number" min="0" max="4" value="4" /> <button id="insertFront">插入到此元素前面</button> <button id="insertBack">插入到此元素后面</button> <div id="main"> </div> </body> <script type="text/javascript"> $(function(){ var mainDiv=$("#main"); for(var i=1;i<6;i++){ var $divs=$("<div class='div' id='a"+i+"'>我是第"+i+"个</div>") mainDiv.append($divs) } var newDiv=$("<div class='newDiv'>我是新的</div>"); var front=$("#insertFront") var back=$("#insertBack") front.click(function(){ var numVal=parseInt($("#num").val()); var div1=document.getElementById("a"+numVal+""); newDiv.insertBefore(div1) }) back.click(function(){ var numVal=parseInt($("#num").val()); var div1=document.getElementById("a"+numVal+""); newDiv.insertAfter(div1); }) }) </script> </html>
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17