在视口中保留一个绝对定位的元素(jquery) [英] keep an absolutely positioned element in viewport (jquery)

查看:71
本文介绍了在视口中保留一个绝对定位的元素(jquery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用大量工具提示在网站上工作。我想确保工具提示始终完全显示在视口中。

I am working on a site now with a lot of tooltips. I want to ensure that the tooltips will always show up fully in the viewport.

我知道工具提示有插件,但它们对我不起作用,因为工具提示-ing是通过css完成的(我无法改变所有这些!)。你想获得工具提示的任何元素都有一个位置:relative,紧接着是一个带有class ='tooltip'的元素 - 这里是css代码:

I know there are plugins for tooltips, but they won't work for me because the tooltip-ing is done via css (and I can't go change all of them!). Any element that you want to get a tooltip is given a position:relative, and is immediately followed by an element with class='tooltip' - here is the css code:

.tooltip{
    display:none;
    color: #262626;
    background-color: #FEFEE0;
    padding: 5px 12px;
    position: absolute;
    box-shadow: 0 0 5px #A6A6A6;
    margin-top:-8px;
    z-index: 1000;
}
*:hover + .tooltip {
    display:block ! important;
}
.tooltip:hover{
    display:block;
}

我想做的是,每次显示工具提示时(或每当工具提示前的元素悬停时,运行一个函数来计算偏移并确保它适合屏幕(或移动它,如果没有)。

What I would like to do is, every time a tooltip is displayed (or every time the element before the tooltip is hovered), run a function to calculate the offset and make sure it fits in the screen (or move it, if not).

我现在唯一能想到的就是我没有尝试过这样的事情:

The only thing I can think of now that I didn't try yet is running something like:

$("*:hover").each(function(e){
  if ($(this).next().hasClass('tooltip')
    //run some positioning function
}

好的,所以我不是jquery专家,可能是上面的错误,我还没试过,但是你明白了。但是它有意义吗?它会影响性能(以一种糟糕的方式)吗?

Ok, so I'm no jquery expert and could be that the above is buggy, I didn't try it yet, but you get the idea. But does it make sense? Would it impact performance (in a bad way)?

我花了几个小时研究这个问题并且出现了非常感谢任何想法!

I've spent hours working on this and coming up empty. Any ideas greatly appreciated!

推荐答案

你的问题有一个更简单的解决方案。你可以使用 position:fixed; 定位e根据视口的说法。据我所知,它只会在Internet Explorer 7中失败,因此如果您关心这一点,则需要使用IE7技巧来模拟固定定位。此外, * 选择器以及您在那里所做的事情无疑会对性能产生影响。
这个是阅读CSS和JS分析的好地方。请注意,它详尽无遗,但绝对值得一读。

There is a far more simple solution to your problem. You can use position:fixed; to position an element according to the viewport. It will only fail in Internet Explorer 7, as far as I know, so if you care about this, you need to use an IE7 trick to simulate fixed positioning. Also, * selectors and what you are doing there will undoubtedly impact on performance. This is a good place to read about CSS and JS profiling. Beware, it is exhaustively detailed, but definitely worth reading.

这篇关于在视口中保留一个绝对定位的元素(jquery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆