我定义了名为"slide-1“和"slide-2”的div,如果单击第一个按钮,则具有一个称为"option-1“的中间跨度。
我想将scrollTop动画中的195和268 (见下文)更改为基于"slide“div的高度计算的数字,但当我尝试("#slide-2").height()例如它似乎不起作用。
这是我到目前为止所拥有的CodePen,它完全按照我想要的方式工作,但是我担心一旦我将它添加到网页上,我将不得不再次手动更改scrollTop编号
现在,滚动是基于我自己输入的数字
//first option code
$("#option-1-button").on("click", function() {
$(this).closest(".box").find("#option-1").slideToggle();
$('body').animate({scrollTop: 195}, 1000);
$("#slide-2").delay(500).fadeToggle(1000);
$('body').delay(500).animate({scrollTop: 268}, 1000);
$('#option-1-button').prop('disabled', true);
$('#option-2-button').prop('disabled', true);
});发布于 2016-07-28 04:34:23
我想你只是漏掉了$符号:
$('body').animate({ //animate element that has scroll
scrollTop: $("#slide-1").height() //for scrolling
}, 1000);
$("#slide-2").delay(500).fadeToggle(1000);
$('body').delay(500).animate({ //animate element that has scroll
scrollTop: $("#slide-2").height() //for scrolling
}, 1000);发布于 2016-07-28 04:37:02
您可以使用offset()获取div的位置;它将提供元素的顶部或左侧位置。(文档0,0的顶部或左侧的像素),然后滚动到该值。
例如$('#slide-1').offset().top;
发布于 2016-07-28 04:49:11
这里有几件事你需要注意-
ID值。在id="windows"中有2个元素。将它们更改为类,否则高度将为off。windows元素,它们可能都具有不同的高度,因此您将需要依赖索引值来确定将获得的windows高度。- The height of the `option` box to the top of the window
- The height of the `option` box itself including margin
- The height of the `windows` element including margin
var window = $('.windows')[0] //0 is the index of the first occurrence of the class windows
var scrollHeight = $('#option1').offset().top + $('#option1').outerHeight(true) + $(window).outerHeight(true);我利用了jQuery方法.outerHeight([includeMargin])并将includeMargin标志设置为true,因此它将包含计算height - http://api.jquery.com/outerheight/时所需的任何页边距
https://stackoverflow.com/questions/38622521
复制相似问题