在bootstrap模态内的元素上使用offset返回零

时间:2017-01-23 07:54:04

标签: javascript jquery twitter-bootstrap-3 html5-canvas bootstrap-modal

使用html画布制作应用程序。我尝试使用jquery的.offset()方法获取画布的偏移量,这没关系。我的问题是,当我尝试将画布放在模态上时,offset()返回0 ...如何在boostrap模式中获得画布的正确偏移量?

canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvasOffset=$("#canvas").offset();
offsetX=canvasOffset.left;
offsetY=canvasOffset.top;

canvasOffset返回top和left为零...

1 个答案:

答案 0 :(得分:3)

您必须等待使用shown.bs.modal事件通过引导程序定位模态。模态之前没有定位,因此画布的位置为0。

检查此样本:

// As soon as the modal is shown
$('#myModal').on('shown.bs.modal', function() {
  // Get the right offset
  var offset = $("#canvas").offset();
  $('body').append("<br>offset:" + offset.top + ", " + offset.left);
});

// On page load offset is 0, 0
var offset = $("#canvas").offset();
$('body').append("<br>offset:" + offset.top + ", " + offset.left);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <canvas id="canvas" width="150" height="150" color="pink"></canvas>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>