gpt4 book ai didi

javascript - 当视口(viewport)中有空间时,将工具提示定位在鼠标上方,否则在鼠标下方

转载 作者:行者123 更新时间:2023-11-28 08:28:51 25 4
gpt4 key购买 nike

我正在创建工具提示,但在定位时遇到了一些问题。

工具提示设置为 position: absolute,我有一个鼠标事件处理程序,它修改它的 topleft CSS,具体取决于pageXpageY

现在,我知道我可以将 top 设置为 pageY 并将 left 设置为 pageX。这将使工具提示弹出到右下角。当有空间时,我试图将它定位在右上角弹出的位置,但如果它在 Y 轴上超出视口(viewport),请再次放到右下角的位置。

目前,我一直在尝试让工具提示显示在鼠标的右上角。我什至不知道从哪里开始检测它是否在视口(viewport)中。谁能指出我正确的方向?

$('p').on('mouseenter', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).detach();
});

Example on JSFiddle

最佳答案

有许多不同的方法来处理工具提示,尤其是在使用 jQuery 时。这种方法可能不是我的首选。但是,以下更改应该会按照您的预期工作。

var tt = document.createElement('div');
tt.id = "tt";

$('p').on('mouseenter', function(e) {
var curPos = $( this ).offset().top - $( window ).scrollTop();
var inView = (curPos < 250) ? 0 : 250;
$(tt).css('top', e.pageY - inView);
$(tt).css('left', e.pageX);
$(tt).append($( this ).attr("data-myId"));
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).empty($( this ).attr("data-myId"));
$(tt).detach();
});

Full changes in JSFiddle .

我正在利用 jQuery 的 offset()scrollTop() 方法来估计当前元素在文档可视区域内的位置。

According to jQuery's API documentation, the .offset() method allows us to retrieve the current position of an element relative to the document. The documentation also states that the vertical scroll position (.scrollTop()) is the same as the number of pixels that are hidden from view above the scrollable area.

我们使用这两种方法来发挥我们的优势,并从元素相对于文档的当前位置减去可滚动区域上方的像素数。需要注意的一件重要事情是 offset 方法返回一个具有属性 top 和 left 的对象。

var curPos = $( this ).offset().top - $( window ).scrollTop();

由于您将 #tt id 设置为静态 250px 高度,我们可以检查当前元素相对于窗口可视部分的位置是否小于 250。如果是,那么我们不减去任何内容并让工具提示位于鼠标位置下方。如果它大于 250,那么我们减去 250px,工具提示将位于当前鼠标位置上方。

我不确定您打算如何引入工具提示的内容,但我还添加了 $(tt).append($( this ).attr("data-myId")); 将 data-myId 值用作工具提示内容, $(tt).empty($( this ).attr("data-myId")); 将其清除鼠标离开。希望对您有所帮助!

关于javascript - 当视口(viewport)中有空间时,将工具提示定位在鼠标上方,否则在鼠标下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com