从一个按钮滚动到不同的ID

时间:2015-01-25 18:50:14

标签: javascript jquery html css

我有不同身份的不同盒子 <div id="49" align="center" class="feed_box_id"></div>
<div id="50" align="center" class="feed_box_id"></div>
<div id="51" align="center" class="feed_box_id"></div>

我想在点击相同的按钮时滚动下一个id。

我试过了

  • scrollTop的
  • scrollTo
  • window.location.href


但是找不到出路。 如果你愿意,这里是我的模糊代码

var id_down = parseInt($(".feed_box_id").attr("id")) - 1;

  $("#feed_down").click(function() {

     window.location.href = "#" + id_down; 

  });

  var id_up = parseInt($(".feed_box_id").attr("id")) + 1;

    $("#feed_up").click(function() {
     window.location.href = "#" + id_up; 

  });

2 个答案:

答案 0 :(得分:1)

维护一个变量,用于跟踪最后点击的ID。

var lastclicked={id:49};

$("#feed_up").click(lastclicked, function(e) {
    if($("#" + (e.data.id+1)).length>0)
    {
        window.location.href = "#" + (e.data.id+1);
        e.data.id++;
    }
});
$("#feed_down").click(lastclicked, function(e) {
    if($("#" + (e.data.id-1)).length>0)
    {
        window.location.href = "#" + (e.data.id-1);
        e.data.id--;
    }
});

好的,你可以自己创造小提琴。

HTML:

<button id="feed_down">feed_down</button>
<button id="feed_up">feed_up</button>

JS:

for(var i=0;i<100;i++)
{
    $('<div id="' + (i) + '" align="center" class="feed_box_id">'+ (i) +'</div>').appendTo($('body'));
}

var lastclicked={id:49};

$("#feed_up").click(lastclicked, function(e) {
    if($("#" + (e.data.id+1)).length>0)
    {
        window.location.href = "#" + (e.data.id+1);
        e.data.id++;
    }
});
$("#feed_down").click(lastclicked, function(e) {
    if($("#" + (e.data.id-1)).length>0)
    {
        window.location.href = "#" + (e.data.id-1);
        e.data.id--;
    }
});

CSS:

#feed_down
{
    position:fixed;
    top:0;
    right:0
}
#feed_up
{
    position:fixed;
    top:0;
    right:100px
}

答案 1 :(得分:0)

有两种方法:只使用没有id的类,使用id而不需要类 仅限课程:

var elementIndex = 0, elements = document.getElementsByClassName('myClass');
var scrollToElement = function(element){
    window.scrollTo(0, element.getBoundingClientRect().top);
};
var nextElement = function(){
    if(++elementIndex >= elements.length)
        elementIndex = 0;
    scrollToElement(elements[elementIndex]);
};
var previousElement = function(){
    if(--elementIndex < 0)
        elementIndex = elements.length - 1;
    scrollToElement(elements[elementIndex]);
};

仅限Id(可能不仅仅是数字):

var elementIndex = 0, elements = ['id1', 'myDog', 'last'];
var scrollToElement = function(element){
    window.scrollTo(0, element.getBoundingClientRect().top);
};
var nextElement = function(){
    if(++elementIndex >= elements.length)
        elementIndex = 0;
    scrollToElement(document.getElementById(elements[elementIndex]));
};
var previousElement = function(){
    if(--elementIndex < 0)
        elementIndex = elements.length - 1;
    scrollToElement(document.getElementById(elements[elementIndex]));
};