jquery点击滑动到某个位置

原文链接: http://caibaojian.com/jquery-scrollto.html

比较常用的一个功能,只需要一个简单的函数就可以滑动到任意你需要的地方,默认点击之后是返回顶部。

function scrollTo(ele, speed){
	if(!speed) speed = 300;
	if(!ele){
		$("html,body").animate({scrollTop:0},speed);
	}else{
		if(ele.length>0) $("html,body").animate({scrollTop:$(ele).offset().top},speed);
	}
	return false;
}

使用方法:

1.滑动到顶部,速率为0.3秒

scrollTo();

2.滑动某个元素的位置。

a.滑动id为item scrollTo('#item',300);

b.滑到某个标签item scrollTo('.item');

javascript版本

或者某个元素offsetTop兼容代码

//code from http://caibaojian.com/jquery-scrollto.html
function getElementPosition(e) {
            var x = 0, y = 0;
            while (e != null) {
                x += e.offsetLeft;
                y += e.offsetTop;
                e = e.offsetParent;
            }
            return { x: x, y: y };
        }

猜你喜欢

转载自blog.csdn.net/qq_36328915/article/details/80922376