jQuery scrolling div not behaving in Safari (but can replicate in jsFiddle on Chrome)

StackOverflow https://stackoverflow.com/questions/22403268

  •  14-06-2023
  •  | 
  •  

質問

We have a form in a sidebar on one of our pages which is fixed to a position as the visitor scrolls down the page.

I've just been made aware that on Safari, as soon as the visitor scrolls, the form flies way off the bottom of the screen rendering it useless and ineffective as no-one can submit it. It works as expected in Chrome, Firefox, Opera and IE (first for everything) so issue is only apparent in Safari.

That said however, I created a JsFiddle of the scenario, and the same problem that occurs in Safari happens in the Jsfiddle (using Chrome). If you view the jsFiddle and scroll down, you'll see the issue that is occurring.

The jQuery in use is below:-

var $scrollingDiv = jQuery("#vfb_widget-2");
var elemTop = $scrollingDiv.offset().top - 80;

jQuery(window).scroll(function(){
$scrollingDiv.stop();

if (jQuery(window).scrollTop()>elemTop) {
$scrollingDiv.animate({"marginTop": (jQuery(window).scrollTop()-elemTop) + "0px"}, "slow" );
} else {
$scrollingDiv.animate({"marginTop": "0px"}, "slow");
}
});

I'm aware of plenty of other questions on SO that are similar to this and many recommend using html, body instead of window but I've played around with a number of variations with no success so am thinking I haven't got this jQuery exactly right.

On the same website where this form is in place, the header also gets fixed to the top of the page when the visitor scrolls down hence the requirement for the top offset of 80.

If anyone could shed some light on this, it would be greatly appreciated.

役に立ちましたか?

解決

I updated your JSFiddle and i think it is fixed now: http://jsfiddle.net/veritas87/tcTKU/2/

The problem was you were adding "0px" behind the margin-top, so practically you were adding this string 0px after the number that came out. So if the scrolltop-elemtop was 100, you would make it 1000px because of the 0px.

var $scrollingDiv = jQuery("#vfb_widget-2");
            var elemTop = $scrollingDiv.offset().top - 80;

            jQuery(window).scroll(function(){
            $scrollingDiv.stop();

            if (jQuery(window).scrollTop()>elemTop) {
            $scrollingDiv.animate({"marginTop": (jQuery(window).scrollTop()-elemTop) + "px"}, "slow" );
            } else {
            $scrollingDiv.animate({"marginTop": "0px"}, "slow");
            }
            });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top