jQuery scrollTop in container on click only works once

天大地大妈咪最大 提交于 2020-12-13 12:16:03

问题


I'm trying to make a content slider of sorts with the simplest jQuery possible, without a plugin and without assigning ids to each div.

I have a fixed position #container that is 100% width and 45% height of the page and contains 5 divs called .sect. all 5 .sect are 100% width of the container and are also 45% height of the page, which means that 1 .sect would fill the visible portion of #container, when scrolled to.

a div #down outside #container should, on click, make the #container scroll to each of the .sects. this is my jQuery for it. I set the value of scrollTop to the height of .sect so that #container will scroll the exact height of each sect every time it is clicked.

$('#down').on('click', function(e) {
    e.preventDefault();
    $('#container').animate({ scrollTop:$('.sect').height()  })
});

the first time #down is clicked, #container scrolls from the 1st .sect in view to the 2nd .sect with no problem, but after that, #down doesn't do anything anymore. jsfiddle - the html and css aren't notable, i think. I'm new to jQuery so please explain what i'm missing!


回答1:


I think you are missing that the container should keep scrolling depending on how much of scroll it has done, your code only scrolls down to the height of 1 .sect it should be like:

ScrollTop: scrolled + height

scrollTop: $("#container").scrollTop() + $(".sect").height();


来源:https://stackoverflow.com/questions/37084343/jquery-scrolltop-in-container-on-click-only-works-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!