首页 > 解决方案 > 使用 javascript 而不是 JQUERY 将图像放入购物篮

问题描述

我正在尝试做飞行购物车,这意味着当单击“添加到购物车”按钮时,产品图像应被视为克隆并飞入篮子。和这个视频一样

Youtube 视频

该视频的代码为

$("button").on("click",function(){
$(this).closest("li")
.find("img")
.clone()
.addClass("zoom")
.appendTo("body");

setTimeout(function(){
$(".zoom").remove();
},1000);
});

我应该在没有 Jquery 的 javascript / html 中做同样的事情。

我的尝试

  var itm1 = document.getElementById("one");
  // HEre I can take the clone of the image.
  var cln1 = itm1.cloneNode(true);
  // Here I need to add the css to this image as per the video.

标签: javascriptjqueryhtmlcss

解决方案


您只需找到元素,复制它,将其添加到文档中,然后添加具有动画的类。

这是一个工作示例:

document.querySelectorAll(".item").forEach(function(item) {
  item.querySelector(".add").addEventListener("click", function() {
    document.body.appendChild(item.querySelector(".image").cloneNode()).classList.add("floating");
  });
});
.image {
  height: 40px;
  width: 40px;
}

.image.floating {
  animation: fade-out-in-right 2s linear 0s 1 normal forwards;
  position: absolute;
  right: 20px;
  top: 20px;
}

@keyframes fade-out-in-right {
  0% {
    transform: translateX(-100px);
    opacity: 0;
  }
  80% {
    transform: translateX(-20px);
    opacity: 1;
  }
  100% {
    transform: translateX(0px);
    opacity: 0;
  }
}
<div class="item">
  <div class="image" style="background: blue"></div>
  <button class="add">Add To Cart</button>
</div>
<div class="item">
  <div class="image" style="background: red"></div>
  <button class="add">Add To Cart</button>
</div>


推荐阅读