开发者

Safari inserts an odd object into the DOM when shrinking window that messes up jQuery's position() results

in developing a more complicated script I am having a rather odd problem with Safari. I use 5.0.5 Win if it matters. I rely on jQuery's position().left when the browser window gets resized to reposition a position:fixed element. Depending on wether the window is being enlarged or shrinked I get different results for position().left though because of some odd element being rendered by Safari at that moment (and only at that very moment).

I wrote a demo page that shows the problem.

Safari inserts an odd object into the DOM when shrinking window that messes up jQuery's position() results

Load the source below in Safari in windowed mode and shrink the window a bit. The alert will make things freeze so that you will see the the odd element that troubles me in the top left corner of the document.

What on earth is that, where does it come from and how do I get around it?

Thanks.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
  <head>
    <style type="text/css">
    #test{
        width:500px;
        height:2000px;
        margin: 0 auto;
    }
    </style>
        <script type="t开发者_StackOverflow中文版ext/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
    <script type="text/javascript">
    // <![CDATA[
        function resizeWindow( e ) {
            alert($('#test2').position().left);
        };
        $(window).bind("resize", resizeWindow);
    // ]]>
    </script>
  </head>
  <body>
  <div id="test"><div id="test2">Something
  </div></div>
</body></html>


I figured out what to do to make this stop: Explicitly setting the body's width to 100% by css does it. What the odd element is and why it is injected without this in the first place, I still have no idea though.

body {
    width:100%;
}

This solution inevitably adds a horizontal scroll bar. So I added a class

body.safariFix
{
    width:100%;
}

and assign that by JS before getting the values I need and afterwards I remove it again.

if ($.browser.webkit) $('body').addClass('safariFix');
    ...
if ($.browser.webkit) $('body').removeClass('safariFix');

The browser detection part was added because doing this caused an infinite loop in MSIE. This is inside the resize event handler after all and removing / adding the class lets MSIE fire the resize event. I'm not using feature detection because I don't know which feature to detect for spotting this. Detecting the odd display object would be nice but I did not look into that further.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜