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

Scroll to different id(s) from one button

本文关键字:ID 滚动 按钮 一个      更新时间:2023-09-26

我有不同的盒子,有不同的id

<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。

我试过了

  • 滚动顶部
  • 滚动到
  • 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; 
  });

维护一个变量,用于跟踪上次点击的 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
}

有两种方法:只使用没有 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]));
};