开发者

jquery: calculating 'margin-left' or 'left' relative to $(window).scrollLeft() is really jagged in Firefox — using .animate() or .css()

I have a horizontally scrolling website, and I have a block that I want to stay in frame at all times as the user scrolls right. It looks perfectly smooth in webkit browsers, but is crazy jagged in Firefox and I don't really care about IEs.

function fixMyId(){
   $('#myId').css({'margin-left': 150 + $(window).scrollLeft()});
}

function fixMyIdAlt(){
   $('#myId').stop().animate({'margin-left': 150 + $(window).scrollLeft()}, 300);
}

And then I have it triggered on window开发者_如何学运维 scroll.

What would be a best way to average out the scrolling, so that maybe every so many seconds or pixels of scrolling it fires the function, or upon stopping the scrolling it animates the block into place? I tried playing with delay() but that doesn't do anything. And this one just looks stupid (plus I have no idea what the overhead of this kind of crunching is):

function fixMyIdStupid(){
    window.scrollCounter++;
    if(window.scrollCounter % 20 == 0) $('#myId').stop().animate({'margin-left': 150 + $(window).scrollLeft()}, 300);
}

So what do I do? setTimeout and setInterval may be required, but those always make my head hurt.

EDIT: Here's a jsfiddle of it in action: http://jsfiddle.net/xsxSq/

The #f0f square is the #myId.


I tried to do such things as well, problem is that the scroll event isn't fired as much as you want. A nice workaround was subscribing the calculation function to the mousemove event, so it triggers A LOT. But on the other hand, I came up with another solution.

Why not turn things around and ask yourself: Lets make it a position:fixed object and calculate what happens on resize. Because you actually are trying to create a position-x:fixed; and a position-y:absolute;

I actually did the following for the opposite kind of thing. A block that has to be exactly in the middle of the x-document, but in the y it was fixed.

$(document).ready(function ()
{
    replaceFixed();

    $(window).resize(replaceFixed);
    $('#content').ajaxSuccess(replaceFixed);
    $(window).scroll(replaceFixed);

    function replaceFixed()
    {
        var jEl = $('#centeredFixedContainer');

        var winW = $(window).width();
        var docW = $(document).width();
        var scrL = $(window).scrollLeft();
        var divW = jEl.width();

        var result = 0;

        // window bigger than the element
        if(winW > divW)
        {
            result = -scrL + ((docW-winW)/2);
        }
        else
        {
            result = $('#mainContainer').offset().left - scrL;
        }


        jEl.css('left',result);
    }
});

Copying this code will not give you the solution, but will indicate another way to look at your problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜