开发者

Adjusting window scroll position in JavaScript to counteract element's resizing above

I'm trying to counteract an adjustment to the height of an element which is above the scroll offset by calculating the difference in height and then updating the current scroll position to account for it.

The problem is that there's no way that I can prevent a very quick flickering artefact. Whether I adjust the element's height and then the scroll position, or vice versa, I can't seem to prevent a quick visual jump.

Does anyone know how this could be overcome? I want these to operations to happen at the same time with no rendering in-between 开发者_开发问答but I'm not sure if it's possible.

// Setup
...
var myElement = ...
var oldHeight = ...
var scrollOffset = window.scrollY;
var newHeight = 100;
var diff = newHeight - oldHeight;

// Determine if we need to counteract new size
var adjustScroll = (absoluteOffset(myElement) < scrollOffset);

// Adjust size
myElement.style.height = newHeight+'px';

// Adjust scroll to counteract the new height                    
if (adjustScroll) window.scrollTo(0, scrollOffset+diff);

I'm working with WebKit, specifically on iOS.


for webkit you can use CSS transitions/animations to smooth this but it's still sound like you are going the wrong way to begin with. I am sure that whatever is it you are trying to do can be solved purely with CSS (maybe with some very minimal Javaqscript). Post an example of you HTML + CSS + JS.


You could use scrollIntoView with timers to simulate multiple threads.
Or you could do it inside a document fragment beforehand.


Sorry to be reviving an old post here, but i came across this looking for a solution to a similar problem to do with browser resizing.

Stackoverflow user James Kyle created this little jsfiddle using jQuery that attempts to maintain scroll position as best as possible when a page is resized

var html = $('html'),
    H = html.outerHeight(true),
    S = $(window).scrollTop(),
    P = S/H;

$(window).scroll(function() {
    S = $(window).scrollTop();
    P = S/H;
});

$(window).resize(function() {
    H = html.outerHeight(true);
    $(window).scrollTop(P*H);
});

http://jsfiddle.net/JamesKyle/RmNap/

you could try using this same code and trigger a 'resize' event on the html when the image has loaded by using a jQuery library like imagesLoaded

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜