javascript 使用 jQuery 悬停时工具提示的 CSS 动态位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6061317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:19:27  来源:igfitidea点击:

CSS dynamic position of tooltip on hover with jQuery

javascriptjqueryhtmlcsstooltip

提问by Narazana

I'm writing a simple tooltip that can hold HTML tags. Please check http://jsfiddle.net/Qkwm8/for the demo.

我正在编写一个可以包含 HTML 标签的简单工具提示。请查看http://jsfiddle.net/Qkwm8/以获取演示。

I want the tooltip box to show properly regardless of the position of element, in this case <a>, that shows tooltips on mouseover event.

无论元素的位置如何,我都希望工具提示框正确显示,在本例中<a>,显示鼠标悬停事件的工具提示。

The tooltips are shown fine except when <a>floats right (or is at the end of the line) or at the bottom of the screen where it doesn't show properly, it appears off the screen

工具提示显示正常,除非<a>向右浮动(或在行尾)或在屏幕底部显示不正确,它会出现在屏幕外

If the <a>floats right, or at the end of the line, or is at the bottom of the screen, I want the tooltip to change position so it remains visible

如果<a>浮动右侧,或在行尾,或在屏幕底部,我希望工具提示更改位置以使其保持可见

Thank you.

谢谢你。

Update demo link

更新演示链接

here's the complete result: http://jsfiddle.net/Qkwm8/3/

这是完整的结果:http: //jsfiddle.net/Qkwm8/3/

回答by Vincent Ramdhanie

You can use the document width to check how wide the html document is and adjust the left position accordingly. Say:

您可以使用文档宽度来检查 html 文档的宽度并相应地调整左侧位置。说:

    //set  the left position
    var left = $(this).offset().left + 10;
    if(left + 200 > $(document).width()){
        left = $(document).width() - 200;   
    }

I used 200 here because you are setting your tooltip to 200px wide. Something similar can be done with height.

我在这里使用了 200,因为您将工具提示设置为 200 像素宽。可以用高度做类似的事情。

There is also a window width but I always get confused about the difference so you should check which one gives you better results.

还有一个窗口宽度,但我总是对差异感到困惑,所以你应该检查哪个给你更好的结果。

An example of the bottom of the page is:

页面底部的一个例子是:

   //set the height, top position
    var height = $(this).height();
    var top = $(this).offset().top;
    if(top + 200 > $(window).height()){
        top = $(window).height() - 200 - height;
    }

Again, using 200 since you are setting your tooltip to 200px height.

再次使用 200,因为您将工具提示设置为 200px 高度。

回答by Ben

$('a.show-tooltips').mouseover(function() {

$('a.show-tooltips').mouseover(function() {

if(($(this).parent()).css('float')) =="right") add the proper class to left

if(($(this).parent()).css('float')) =="right") 向左添加适当的类

else -> the proper class the right .... }

否则 -> 正确的类是正确的.... }