带有样式属性的jQuery clone clone元素

时间:2019-02-17 11:19:22

标签: javascript jquery clone

我想制作可拖动的历史记录。当可拖动停止时,应将整个DOM推送到let history = [],然后每当有人单击button时,应将最后一个DOM带回,但它不起作用。当我尝试恢复以前的DOM时,它无法正确克隆。似乎style="top: , left:"属性未克隆。有人可以帮忙吗?

let history = [];

function pushHistory() {
  history.push($('.page').each(function() {
    return $(this).clone(true, true)
  }))
}

function backHistory() {
  history.pop();
  $(history[history.length - 1]).each(function() {
    $(this).detach().appendTo($('.outer'))
  })
}
$(".page").draggable({
  stop: function(event, ui) {
    pushHistory();
  }
})

$('button').on('click', function() {
  backHistory();
})
.page {
  display: inline-block;
  background-color: red;
  width: 50px;
  height: 50px;
  position: relative;
  color: white;
  font-size: 3em;
  text-align: center;
  line-height: 50px;
}

.back {
  position: absolute;
  top: 0px;
  right: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="outer">
  <div class="page">
    1
  </div>
  <div class="page">
    2
  </div>
  <div class="page">
    3
  </div>
  <div class="page">
    4
  </div>
  <div class="page">
    5
  </div>
  <div class="page">
    6
  </div>
</div>
<button class="back">
Back
</button>

1 个答案:

答案 0 :(得分:1)

我对JavaScript部分做了如下调整,并且可以正常工作:

let history = [];

function pushHistory(el) {
    history.push({
        index: el.index(),
        offset: el.offset()
    })
}

function backHistory() {
    let el = history[history.length - 1];
    if (el) {
        $('.outer').find('.page').eq(el.index).offset(el.offset);
        history.pop();
    }
}

$('.page').draggable({
    start: function() {
        pushHistory($(this))
    }
})

$('button').on('click', function() {
    backHistory();
})

基本上,它现在在可拖动的“开始”事件上保存元素的索引和偏移量。然后,backHistory仅作用于最后拖动的元素。

它在这里运行:https://jsfiddle.net/12sdku0e/

相关问题