如何获得可滚动窗口视口的相对尺寸

时间:2009-07-08 13:04:49

标签: javascript jquery

我正在通过e.pageX e.pageY定位工具提示(更大的图像视图),我正在尝试确保它不会隐藏在当前滚动视图端口下方。

我见过很多网站都有这个 我的代码是这样的,但我错过了一些东西。

var positionImg = function(e) {
    var viewportWidth = $(window).width(); 
    var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();  
    var mouseAtY = e.pageY;
    var mouseAtX = e.pageX;
    var maxBottomVPos = viewportHeight-"i dont know";
    var maxTopVPos = 30;

    if (mouseAtY >= maxBottomVPos)
    {
        tPosX = mouseAtX+ 10;
        tPosY = mouseAtY -520;
    }
    else if (mouseAtY <= maxTopVPos)
    {
        tPosX = mouseAtX;
        tPosY = mouseAtY +40;
    }
    else
    {
        tPosX = mouseAtX;
        tPosY = mouseAtY +20;  
    }
    $zoomContainer.css({top: tPosY, left: tPosX});
};

2 个答案:

答案 0 :(得分:1)

  

var maxBottomVPos = viewportHeight-"i dont know";

您可能不希望任何低于您定位的元素的高度。因此,使用zoomContainer的高度来计算它需要多高。这样,整个事情都可以包括在内。当然,您必须考虑用户可能将屏幕缩小得太小而无法容纳容器。

要获取滚动偏移,请使用scrollTop。通过此操作,您将同时具有视口大小和视口下方的距离。

答案 1 :(得分:0)

我找到了答案:

非常简单: var positionImg = function(e){             cntnrH = $ zoomContainer.height()+ 230;             calHight = e.pageY - $(window).scrollTop()+ cntnrH;             docH = $(窗口).height()

        var mouseAtY = e.pageY;
        var mouseAtX = e.pageX;

      if (calHight >= docH)
         {
        tPosX = mouseAtX + 5;
        tPosY = mouseAtY - cntnrH;
         }
 else if (calHight <= calHight){
           tPosX = mouseAtX;
       tPosY = mouseAtY + 15;
      }
      else
      {
       tPosX = mouseAtX;
       tPosY = mouseAtY +20;  
      }
      $zoomContainer.css({top: tPosY, left: tPosX});
      };
     doIt = $("img.hovelble");
     doIt.hover(showZoomImg, hideZoomImg).mousemove(positionImg);
});