How to know when an element will be off screen?

不羁岁月 提交于 2020-01-24 02:08:18

问题


I am writing a simple script that displays a dialog box when a user hovers over a profile picture. It dynamically determines the profile pics location on the page and then places itself to the left of it and about 100px above it. This part is working fine.

My issue arises when a profile pic is at the top of the screen and a user mouses over it. The dialog will appear but the top portion of it will be above the fold (i.e. not in the current browser window). Naturally this is not good usability and I would like it to appear on the screen.

My question is how do I know when a dialog will be off screen so I can recalculate its position on the page?

I saw this question which seems like the same as mine but unfortunately no actual solution was provided other then to link to a jQuery plugin. I am using Prototype.


回答1:


Prototype already provides positions with Element.viewportOffset().

Edit, as Mathew points out document.viewport gives the rest of the information. For example,

var dialogtop = dialog.viewportOffset().top;
if (dialogtop < 0) {
    // above top of screen
}
elseif (dialogtop + dialog.getHeight > document.viewport.getHeight()) {
    // below bottom of screen
}



回答2:


You'll want to find the profile pic's position relative to the document (here's a good article on how, though I suspect Prototype's Element.Offset already handles this), then compare it to the body's scrollTop property to see if it's close enough to the top that it needs to have its dialog repositioned.




回答3:


I am familiar with this problem, however, last time I was able to use a library (Seadragon) to get the screen dimensions and mouse position. I was also working with a fixed size overlay so no code to share with you other than general approach.

For my pop up box I decided to use the event mouse position rather than location of the div on the page. I then compared the mouse position to the known screen size, which I determined on start or resize.

From How do I get the size of the browser window using Prototype.js?

var viewport = document.viewport.getDimensions(); // Gets the viewport as an object literal
var width = viewport.width; // Usable window width
var height = viewport.height; // Usable window height

In Prototype you can also get the mouse coordinates:

function getcords(e){
mouseX = Event.pointerX(e);
mouseY = Event.pointerY(e);
//for testing put the mouse cords in a div for testing purposes
$('debug').innerHTML = 'mouseX:' + mouseX + '-- mouseY:' + mouseY;
}

Source : http://remorse.nl/2008/06/mouse_coordinates_with_prototype/



来源:https://stackoverflow.com/questions/6294284/how-to-know-when-an-element-will-be-off-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!