当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Get Mouse Position or Element Position

问题描述:

I am working on a tooltip plugin with the following options:

  1. Mouse = True|False. Tooltip position relative to Mouse or Element;

  2. Static = True|False. Follow mouse when option Mouse = true.

I have a JSFiddle example in: http://jsfiddle.net/mdmoura/RPUX6/

THE PROBLEM:

When I place the mouse over the last tooltips of the list the position is wrong.

This happens every time I have scrolled the page ... I have no idea why.

The part of the code which sets the position is:

$(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' });

You can also see the code and the demo in http://jsfiddle.net/mdmoura/RPUX6/.

Thank You!

网友答案:

You need to account for scrollTop and scrollLeft of the window.

Basic idea:

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

Add scrollTop by

document.body.scrollTop

And you will be good to go..

In your code make these changes

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

})

分享给朋友:
您可能感兴趣的文章:
随机阅读: