2013-09-25 21 views
1

我有这个脚本是我想让它的滚动到15%顶部的偏移量。我尝试了很多东西,所以我很好奇你们会采取什么样的方法。我已经把它简化为什么可行,因为我所有的尝试都失败了。希望有人能帮助我。jquery偏移%而不是px - 可能吗?

$('a[href*=#]').bind('click', function (e) { 
     e.preventDefault(); 

     var target = $(this).attr("href"); 

     $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 800, function() { 
      location.hash = target; 
     }); 

     return false; 
    }); 

我在这里做一个小提琴:http://jsfiddle.net/77rFz/

回答

0

我没有尝试,但我要说的是这样可以工作:

$('a[href*=#]').bind('click', function (e) { 
    e.preventDefault(); 

    var target = $(this).attr("href"); 

    var offset = $(target).offset().top - $(target).height * 0.15; 

    $('html, body').stop().animate({ scrollTop: offset }, 800, function() { 
     location.hash = target; 
    }); 

    return false; 
}); 
+0

它不是做得很好,看到这个小提琴:http://jsfiddle.net/77rFz/ – implum

+0

如果我删除的位置.hash =目标它停止闪烁,但然后它开始失误,当我打链接2,3等 – implum

+0

真的,我已经更新了jsFiddle(http://jsfiddle.net/77rFz/44/),并会更新上面的答案 – mvieghofer

0

尝试是这样的

Math.round(parseInt($(target).offset().top) * 0.15) 
+0

不工作或者 - 在这里看到:http://jsfiddle.net/77rFz/ – implum

0

这工作!

$('a[href*=#]').bind('click', function (e) { 
     e.preventDefault(); 

     var target = $(this).attr("href"); 
     var parentDiv = $(this).parent(".wrap1"); 
     var offset = Math.round(parseInt($(target).offset().top) - (0.15 * parentDiv.height())); 

     $('html, body').stop().animate({ scrollTop: offset }, 800, function() { 
      //location.hash = target; 
     }); 

     return false; 
    }); 
+0

我刚刚几分钟前就更新了我的答案。顺便说一句''location.hash = target'不应该有任何问题 – mvieghofer

+0

你没有设置'parstInt'函数的基数。文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – Jasper