2012-07-09 102 views
0

我有一个具有以下功能的页面:有一个大的图像可生成scoll(水平和垂直)和一个固定位置的按钮(它保留在左上角,即使使用滚动),点击时,图像适合客户端宽度。使用固定位置的按钮将图像适合宽度

由于position: fixed在网络不支持Explorer 8中,我使用了一个解决办法 - 这是功能:

function setFixedPosition(jqueryWrapper, pixelsFromTop, pixelsFromLeft) { 

    jqueryWrapper.css('position', 'absolute'); 

    var setOffsets = function() { 
     jqueryWrapper.css("top", (($(window).scrollTop() + pixelsFromTop) + "px")); 
     jqueryWrapper.css("left", (($(window).scrollLeft() + pixelsFromLeft) + "px")); 
    }; 

    setOffsets(); 

    $(window).scroll(function() { 
     setOffsets(); 
    }); 
} 

setFixedPosition($('#zoomFitButton'), 15, 15); 

这是按钮的动作:

$('#zoomFitButton').click(function() { 
    $('img.preview').css('width', '100%'); 
}); 

按钮保持不变无论是在Firefox 13和IE8。

但是,IE8下,如果我的地方滚动,然后我点击按钮,该按钮移动到一个“奇怪”的位置:

  • 如果我垂直滚动,然后点击,它把在按钮左下角;
  • 如果我水平滚动,然后点击,它把按钮在右上角;
  • 如果我滚动两种方式,然后点击,它把按钮某处中心。

在Firefox中,即使在单击适合宽度按钮之后,按钮仍然位于左上角(我期望它的位置)。

这里是a test page

我的代码是否适合此功能(原则上),或者我需要添加一些适合宽度操作(以修复我的按钮定位);或者IE浏览器出现问题(我需要一种解决方法 - 如果有的话,有什么建议吗?)?

谢谢。

+1

http://stackoverflow.com/questions/1628265/how-to-get-positionfixed-css-to-work-in-ie-7-with-transitional-doctype – Austin 2012-07-09 17:08:59

+0

@奥斯汀感谢,它在IE8(并可能在7)。我还是想找到什么是错我的解决办法,特别是如果某些客户端将使用IE6。 – 2012-07-09 17:25:51

回答

0

我发现,在IE6也有效的解决方案。

我认为这个问题与IE没有更新文档大小后更新scrollTop和scrollLeft位置有关。
因此,在调整图片大小后,我必须滚动到左上角(scrollTop(0)和scrollLeft(0))。
不幸的是,如果我有一张需要垂直滚动的大图片,即使它适合宽度,解决方法也会将我带到页面的顶部。所以我添加了代码,可以按比例将我恢复到之前的接近位置。我裹逻辑更通用的功能:

function doSomethingThatAffectsScrollPosition(affectingScrollPositionFunction) { 

    var oldDocumentWidth = $(document).width(); 
    var oldScrollFromLeft = $(window).scrollLeft(); 

    var oldDocumentHeight = $(document).height(); 
    var oldScrollFromTop = $(window).scrollTop(); 

    affectingScrollPositionFunction(); 

    var newDocumentWidth = $(document).width(); 
    var widthRatio = (newDocumentWidth/oldDocumentWidth); 
    var newScrollFromLeft = (oldScrollFromLeft * widthRatio); 

    var newDocumentHeight = $(document).height(); 
    var heightRatio = (newDocumentHeight/oldDocumentHeight); 
    var newScrollFromTop = (oldScrollFromTop * heightRatio); 

    $(window).scrollLeft(0); // Needed for button repositioning 
    $(window).scrollLeft(newScrollFromLeft); 

    $(window).scrollTop(0); // Needed for button repositioning 
    $(window).scrollTop(newScrollFromTop); 
} 

我在适合宽度按钮的动作中使用的功能:

$('#zoomFitButton').click(function() { 
    doSomethingThatAffectsScrollPosition(function() { 
     $('img.preview').css('width', '100%'); 
    }); 
}); 

Here是一个测试页面。