获取鼠标位置或元素位置
问题描述:
我与以下选项的工具提示插件工作:获取鼠标位置或元素位置
鼠标= TRUE | FALSE。工具提示相对于鼠标或元素的位置;
Static = True | False。当选项Mouse = 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/演示。
谢谢!
答
您需要注册该窗口的scrollTop和scrollLeft。
基本思想:
var win = $(window);
$tooltip.css({
left: position[0] + win.scrollLeft() + 'px',
top: position[1] + win.scrollTop() + 'px'
});
答
添加scrollTop的由
document.body.scrollTop
你会好到哪里去..
在您的代码进行这些更改
功能(){ if(o ptions.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;
})
它的工作原理!谢谢 – 2013-04-24 15:56:52