【问题标题】:Get Mouse Position or Element Position获取鼠标位置或元素位置
【发布时间】:2013-04-24 15:06:52
【问题描述】:

我正在开发一个带有以下选项的工具提示插件:

  1. 鼠标 = 真|假。相对于鼠标或元素的工具提示位置;

  2. 静态 = 真|假。鼠标= true时,请按照鼠标。

我有一个 JSFiddle 示例:http://jsfiddle.net/mdmoura/RPUX6/

问题:

当我将鼠标放在列表的最后一个工具提示上时,位置是错误的。

每次我滚动页面时都会发生这种情况......我不知道为什么。

设置位置的代码部分是:

$(this).each(function (e) {
  // SOME CODE  

  $this.mouseenter(function (e) {

    var $tooltip =
      $("<div>")
      .attr("class", options.class)
      .html(options.content !== '' ? (typeof options.content === 'string' ? options.content : options.content($this, $tooltip)) : tooltip.title)
      .appendTo('body');

    $this.attr('title', '');

    var position = [0, 0];

    if (options.mouse) {
      position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
    } else {
      var coordinates = $this[0].getBoundingClientRect();       
      position = [
        (function () {
          if (options.offset[0] < 0)
            return coordinates.left - Math.abs(options.offset[0]) - $tooltip.outerWidth();
          else if (options.offset[0] === 0)
            return coordinates.left - (($tooltip.outerWidth() - $this.outerWidth()) / 2);
          else
            return coordinates.left + $this.outerWidth() + options.offset[0];

        })(),
        (function () {
          if (options.offset[1] < 0)
            return coordinates.top - Math.abs(options.offset[1]) - $tooltip.outerHeight();
          else if (options.offset[1] === 0)
            return coordinates.top - (($tooltip.outerHeight() - $this.outerHeight()) / 2);
          else
            return coordinates.top + $this.outerHeight() + options.offset[1];

        })()
      ];
    }

    $tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });

您也可以在http://jsfiddle.net/mdmoura/RPUX6/查看代码和演示。

谢谢!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要考虑窗口的scrollTopscrollLeft

    基本思路:

    var win = $(window);
    $tooltip.css( {
        left: position[0] + win.scrollLeft() + 'px', 
        top: position[1] + win.scrollTop() + 'px' 
    });
    

    【讨论】:

      【解决方案2】:

      添加scrollTop by

      document.body.scrollTop
      

      你会很高兴的..

      在您的代码中进行这些更改

      函数 () { 如果 (options.offset[1] +document.body.scrollTop; 否则 if (options.offset[1] === 0) 返回坐标.top - (($tooltip.outerHeight() - $this.outerHeight()) / 2)+document.body.scrollTop; 别的 返回坐标.top + $this.outerHeight() + options.offset[1]+document.body.scrollTop;

      })

      【讨论】:

        猜你喜欢
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-17
        • 2011-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多