在鼠标单击时打开DIV - 不会出现在屏幕外

时间:2015-12-07 10:30:41

标签: jquery

我再次遇到问题,我试图在鼠标位置打开DIV。在项目中,我正在开展一个定制的对话框。现在,我可以在鼠标位置打开DIV。但我遇到了一些问题:

  • 有时DIV出现在容器外
  • 每当打开firebug(不了解其他开发者工具窗口)时,对话框将部分落后于firebug。

现在,我收到了这段代码:

HTML:

<div class="content">
    <div class="dialog">
      Some content in here...
    </div>

    <a class="first-link">Open first link</a>
</div>

JS:

$(document).ready(function() {
  $('.first-link').unbind('click').click(openDialog);
});

$(document).mousemove(function(e){
  window.mouseX = e.pageX;
  window.mouseY = e.pageY;
});

function openDialog(e) {
  var elem = $('<div class="dialog">hello</div>')
  $('.content').append(elem);

  var x = window.mouseX;
  var y = window.mouseY;

  var windowWidth = $('.content').width();
  var windowHeight = $('.content').height();

  var dialogWidth = $(elem).width();
  var dialogHeight = $(elem).height();

  var calc = windowWidth - (x + dialogWidth);

  if (calc < 0)
  {
    x += calc - 10;
  }

 calc = windowHeight - (y + dialogHeight);

  if (calc < 0)
  {
    y += calc - 20;
  }

  elem.draggable({containment: '.content'});
  elem.css('position', 'absolute').css('top', y).css('left', x);
}

CSS:

body
{
  height: 500px;
}

.content
{
  border: 1px solid #000;
  height: 250px;
  width: 250px;
  overflow: auto;
  position: relative;
  resize: both;
}

.dialog
{
  min-height: 50px;
  width: 150px;
  border: 1px solid #000;
  padding: 5px;
  background-color: #fff;
  z-index: 2;
}

.first-link
{
  position: relative;
  top: 160px;
  left: 5px;
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}

链接到jsfiddle:

http://jsfiddle.net/JoshB1997/qbn0zu8r/5/

我不知道我的计算方式是否正确。

1 个答案:

答案 0 :(得分:0)

为什么让自己变得复杂?我可以给你一个简单的方法吗?使用CSS计算对话框的居中。专注于HTML操作:

$(function() {
  $(".first-link").click(function() {
        $(".content").append('<div class="new-dialog">Hello!</div>');
  });
});

.new-dialog {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
}

小提琴:http://jsfiddle.net/w04g2dov/

相关问题