2013-05-05 176 views
-1

由于css属性,我滚动到div标签的margin-top太多。所以我认为jquery是解决这个问题的最佳解决方案。使用jquery滚动到div ID

我不知道为什么这不起作用,我对Js和Jquery很新。任何帮助我们不胜感激。

下面是对Js的简要介绍。我发现,当你的DIV ID在容器的(“HTML,身体”)更改为('集装箱)

Here is my jsfiddle

 jQuery(document).ready(function($){ 
var prevScrollTop = 0; 
var $scrollDiv = jQuery('div#container'); 
var $currentDiv = $scrollDiv.children('div:first-child'); 

var $sectionid = 1; 
var $numsections = 5; 

$scrollDiv.scroll(function(eventObj) 
{ 
    var curScrollTop = $scrollDiv.scrollTop(); 
    if (prevScrollTop < curScrollTop) 
    { 
    // Scrolling down: 
     if ($sectionid+1 > $numsections) { 
      console.log("End Panel Reached"); 
     } 
     else { 
      $currentDiv = $currentDiv.next().scrollTo(); 
      console.log("down"); 
      console.log($currentDiv); 
      $sectionid=$sectionid+1; 
      console.log($currentDiv.attr('id')); 
      var divid =$currentDiv.attr('id'); 
      jQuery('#container').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow'); 
      } 
    } 
    else if (prevScrollTop > curScrollTop) 
    { 
    // Scrolling up: 
     if ($sectionid-1 == 0) { 
      console.log("Top Panel Reached"); 
     } 
     else { 
      $currentDiv = $currentDiv.prev().scrollTo(); 
      console.log("up"); 
      console.log($currentDiv); 
      $sectionid=$sectionid-1; 
      var divid =$currentDiv.attr('id'); 
      jQuery('html, body').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow'); 

      } 
    } 
    prevScrollTop = curScrollTop; 
}); 
}); 
+0

检查:http://stackoverflow.com/questions/6677035/jquery-scroll-to-element – 2013-05-05 13:09:31

+0

请减磅你的代码提交的相关部分,这将有助于人们试图回答你的问题。 – 2013-05-05 13:11:43

回答

2

我不完全知道你想要什么,但滚动到使用jQuery的<div>比你的代码更简单。

例如这个码替换锚的自动跳跃行为与平滑滚动:

var top = $($this.attr('href')).offset().top - 10; 

I:

$(document).ready(function(e){ 
    $('.side-nav').on('click', 'a', function (e) { 
     var $this = $(this); 
     var top = $($this.attr('href')).offset().top; 

     $('html, body').stop().animate({ 
      scrollTop: top 
     }, 'slow'); 

     e.preventDefault(); 
    }); 
}); 

当然,你可以通过添加或从中去除随意调节top可变也从它的小提琴(在您的HTML上):http://jsfiddle.net/Qn5hG/8/

如果这不能帮助你或你的问题是不同的,请澄清!


编辑

与提琴问题:

  • jQuery的不被引用
  • 如果jQuery框架与 “的onLoad” 选择你不需要jQuery(document).ready()。删除JavaScript的第一行和最后一行。
  • 您的HTML中没有div#container,因此无法检查它在哪里滚动。滚动事件永远不会触发它。
  • 您的HTML无效。最后有很多未封闭的元素和随机标签。确保它是有效的。
  • 很难弄清楚你的小提琴应该做什么。
+0

,工作得很好。我现在正在与偏移玩弄,我还有一些项目关闭。非常感谢! – nil 2013-05-05 15:15:36

+0

@Russell,为什么不接受?这个答案是否有新问题使其无效? – SoonDead 2015-07-07 15:29:28