【问题标题】:Switch Divs between Divs with Animation使用动画在 div 之间切换 div
【发布时间】:2017-02-26 09:19:03
【问题描述】:

我有两个主要的 div top-divbottom-div,我在这两个 div 中有 1-1 个 div,即 top-div 中的 one-divbottom-div 中的 two-div

我有一个切换按钮,用于将one-div 移动到bottom-divtwo-div 中的top-div。它工作正常。但我想展示像one-div 向上移动和two-div 向下移动这样的动画,反之亦然。

这是我的代码。

function swapButtonClicked(clicked_id){
			if(clicked_id == "btn-bottom"){
				document.getElementById('top-div').appendChild(document.getElementById('one-div'));
				document.getElementById('bottom-div').appendChild(document.getElementById('two-div'));
			}else if(clicked_id == "btn-top"){				
				document.getElementById('bottom-div').appendChild(document.getElementById('one-div'));
				document.getElementById('top-div').appendChild(document.getElementById('two-div'));
			}				
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="top-div">
    <div id="one-div">Move1</div>
</div>
<div id="bottom-div">
    <div id="two-div">Move2</div>
</div>

<button id="btn-top" click="swapButtonClicked(this.id)">To Top</button>
 <button id="btn-bottom" click="swapButtonClicked(this.id)">To Bottom</button>

请给我任何提示或参考。

【问题讨论】:

  • 你的 ("minimal reproducible example") HTML 是什么?你有超过 2.5k 的代表(正如我所写的那样),所以此时这个提示真的没有必要。另外,上面的代码是怎么不工作的,它不应该做什么,它不应该做什么?浏览器的开发者工具有报错吗?
  • 已更新.. 第一次创建 sn-p 所以不知道这一点。
  • appendTo() animation的可能重复

标签: javascript jquery html jquery-animate css-animations


【解决方案1】:

几天前我在做某事时偶然发现了这篇文章:appendTo() animation

将该函数更改为 prependTo 版本我创建了一个小小提琴,这可能是您正在寻找的: https://jsfiddle.net/js30psh0/2/

$.fn.animatePrependTo = function(sel, speed) {
    var $this = this,
        newEle = $this.clone(true).prependTo(sel),
        newPos = newEle.position();
    newEle.hide();
    $this.css('position', 'absolute').animate(newPos, speed, function() {
        newEle.show();
        $this.remove();
    });
    return newEle;
};

$('#swap').on("click", function() {
    var tmp = $('#inner1').parent();
    $('#inner1').animatePrependTo($("#inner2").parent(),2000);
    $('#inner2').animatePrependTo(tmp,2000);
});

您还可以为 animatePrependTo 函数添加一个回调,以便在交换发生时禁用任何涉及交换的按钮。这样你就不会因为按得太快而破坏它。

【讨论】:

  • 这是代码here完全重复,为什么不将问题标记为重复?!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多