在单击时捕获div

时间:2019-05-11 02:09:47

标签: javascript jquery html html2canvas

在我有多个div具有相同类名的环境中,我想使用jquery和HTML2Canvas库捕获一个div元素。

这是一个控制台页面,我想在该页面上为用户提供是否捕获div的额外选择,每个人都不必理会我正在使用的事件监听器。

$('.panel.panel-default', this).one("mouseenter", function() {
  html2canvas(document.getElementsByClassName("panel panel-default")).then(canvas => {
    //document.body.appendChild(canvas);
    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  
    console.log(image);  
    window.location.href = image;
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel one</a><br><br>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel two</a><br><br>
  </div>
</div>
<div class="panel panel-default">
  <div class="panel-body">
    <a> this is panel three</a><br><br>
  </div>
</div>

实际结果应该类似于单击this is panel one时,事件会将该div捕获到文件中。

1 个答案:

答案 0 :(得分:1)

您只需要传递正确的上下文

  $('.panel-body').on("click", function () {
        html2canvas(this).then(canvas => {
            //document.body.appendChild(canvas);
            var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
            console.log(image);
            window.location.href = image;
        })
    });