最近在做webapp時有幾個頁面,都需要同一個效果:錨點跳轉。我認為,在webapp中做錨點跳轉,很別扭,網頁中比較常見的方法,但是在手機端運用卻不合適,那是那個SB的后台,非得讓做成那效果。沒辦法,誰讓人家是老員工了。
使用錨點跳轉做的靜態頁面,沒有一點問題,但是經過他加的php后,就不跳轉了,坑爹的玩意!在調試過程中,找了好多的錨點跳轉的方法,寫在這里,一起分享:
//平滑移動到 想要的位置
$(function() {
var mao = $("#" + getParam("m"));
//獲得錨點
//判斷對象是否存在
if (mao.length > 0) {
var pos = mao.offset().top;
var poshigh = mao.height();
$("html,body").animate({ scrollTop: pos-poshigh-30 }, 3000);
}
});
//根據參數名獲得該參數 pname等於想要的參數名
function getParam(pname) {
// 獲取參數 平且去掉?
var params = location.search.substr(1);
var ArrParam = params.split('&');
if (ArrParam.length == 1) {
//只有一個參數的情況
return params.split('=')[1];
}
else {
//多個參數參數的情況
for (var i = 0; i < ArrParam.length; i++) {
if (ArrParam[i].split('=')[0] == pname) {
return ArrParam[i].split('=')[1];
}
}
}
}
$("html,body").animate({scrollTop: $("#elementid").offset().top}, 1000);
//它代表id為elementid的元素頂端到網頁頂端(不是瀏覽器可視區域頂端)的絕對距離。
$("#elementid").offset().top;
//擴展方法,流暢的滑動
demo: http://jsfiddle.net/9SDLw/
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
// 如果你的元素沒有ID,你想用名字來做定位鏈接,可以使用這個:
$('a').click(function(){
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
// 為了增強性能,你應該將 $('html, body') 選擇器緩存起來。這樣每次點擊時就不需要再重新查找了
var $root = $('html, body');
$('a').click(function() {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
// 如果你想更新當前頁面的URL。在回調里稍微改一下就可以了:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
