jQuery animate scrollTop上升然后退回

时间:2017-01-14 15:58:10

标签: javascript jquery

我有一个函数可以检查页面上是否有任何错误并自动滚动到它们。我遇到的问题是它向上滚动但后来又回到原来的状态。我喜欢它向上滚动并留在那里。

$(".submit_button").click(function (event) {
        event.preventDefault();
        var errorElements = $(".error").filter(":visible");

        if (errorElements.size() > 0) {
            target_top = $(errorElements).offset().top;
            $('html, body').animate({
                scrollTop: target_top
            }, 800);
        }
        return false;
    });

1 个答案:

答案 0 :(得分:2)

问题在于您的选择器。我知道为什么要这样做。任何足够长的Web开发人员都在尽可能多地使用浏览器,但仍然遇到了这个问题。问题是,您使用此选择器连续调用了2个项目<=>

简而言之,更好的方法是检查它是否是animate:scroll浏览器。原因是非WebKit倾向于使用WebKit WebKit 浏览器倾向于使用html (有时候body 。这可能会导致你现在面对的混乱。

简单的短期解决方案是在html回调中使用/WebKit/i.test(navigator.userAgent)之类的内容。这有助于您只为click电话分配一个选择器。

实施例

animate

测试片段

var selector = /WebKit/i.test(navigator.userAgent) ? 'body' : 'html';
$(selector).animate( // ...
$(function() {
	//	simply to make filler divs for scrolling
	for (var i=0;i<10;i++) $('<div />', { 'id': 'div'+i, 'style': 'background-color: '+String.randColorHex()+';' }).append($('.temp').clone().removeClass('temp')).height($(window).height()).appendTo($('body'));
	/*------------------------------------------*/
	
	/***S*O*L*U*T*I*O*N***/
	var divID = 0;
	function btnCheck() {	//	IGNORE, simply to turn buttons on and off when reaching end
		$('#btnScrollDown').prop('disabled', divID>=9);
		$('#btnScrollUp').prop('disabled', divID<=0);
	}
	
	$(document)
		.on('click', '#btnScrollDown', function() {
			if (divID < 10) {
				divID++;
				//	broke everything down so it's easy to see. You can shorten this in a few ways.
/*THIS HERE-> */var selector = /WebKit/i.test(navigator.userAgent) ? 'body' : 'html',
					scrollSelector = '#div' + (divID),
					scrollTop = $(scrollSelector).offset().top
					props = { scrollTop: scrollTop },
					time = 800;
				$(selector).animate(props, time);
				//	simply to turn buttons on and off when reaching end
				btnCheck();
			}
		})
		.on('click', '#btnScrollUp', function() {
			if (divID > 0) {
				divID--
				//	broke everything down so it's easy to see. You can shorten this in a few ways.
/*THIS HERE-> */var selector = /WebKit/i.test(navigator.userAgent) ? 'body' : 'html',
					scrollSelector = '#div' + (divID),
					scrollTop = $(scrollSelector).offset().top
					props = { scrollTop: scrollTop },
					time = 800;
				$(selector).animate(props, time);
				//	simply to turn buttons on and off when reaching end
				btnCheck();
			}
		});
	
});
html, body, div { margin: 0; padding: 0; width: 100%; }
.buttons { display: inline-block; left: 1em; position: fixed; text-align: center; top: 1em; }
button { margin: .25em; padding: .1em .3em; width: 100%; }
.temp { dislpay: none; }