Javascript将多个元素移动到单独的div和back

有3个video,放在3个独立的div中。 还有3个单独的div,但在页面的其他位置(比如contA和contB和contC)。 我希望如果我点击video1,那么video2和video3会转到contA和contB,而video1会转到contC。 如果我再次点击video1,所有video都会回到原来的位置。 如果我点击video2(在contA中),则video1进入contA,video3进入contB,video2进入contC。

我准备了一个jsbin演示: Jsbin DEMO

有人可以帮忙吗? 不胜感激!

编辑:(根据要求添加了代码)

HTML:


first container

second container

third container

JavaScript的:

 $(window).load(function() { //add event for all videos $('.videos').click(videoClicked); function videoClicked(e) { //get a referance to the video clicked var sender = e.target; //get all the videos var $videos = $('.videos'); $videos.appendTo('#contA'); $videos.appendTo('#contB'); //but I need each video to be put to different div: #contA, #contB... $videos.not(sender).appendTo('#contC'); //if I put the clicked video into this container, it does not go back to original one. } }); 

认为这是您正在寻找的,但它基于示例中使用的命名约定。 我也冒昧地将contA / contB和contC重命名为cont1,cont2和cont3,因为它更容易操作。

JSBin演示

  //remember last video clicked (you could check last container instead) var lastclicked; function videoClicked(e) { //get a reference to the video clicked var sender = e.target; //get all the videos var $videos = $('.videos'); if(sender==lastclicked){ //reset to original positions $.each($videos,function(){ var ind = this.id.substring(this.id.length-1); //based on the video + number naming convention $(this).appendTo('#vid' + ind); }); lastclicked = null; return; } lastclicked= sender; var i = 1; //place all non clicked videos in cont1/cont2/etc $.each($videos.not(sender),function() { $(this).appendTo('#cont' + i++ ); }); //place the clicked video in the last container $(sender).appendTo('#cont' + i ); //always cont3 with fixed divs, but this is dynamic in case you add more } }); 

我会编辑这个答案,因为期望的结果变得更加清晰,但我想我可以给你一些信息,让你朝着正确的方向前进。

代码部分“但我需要将每个video放到差异”

我会利用数据属性,让每个控件跟踪自己。

  $video.each(function() { var targetdiv = $(this).data('origonal-div'); $(targetdiv.ToString()).append(this); //optionally update the data value to keep track of the next location to append to. } 

如果您需要更多信息,请在jsbin上更新一些问题,以便我可以看到您遇到问题的地方。

干杯