Javascript 单击后滚动到同级元素
请看一下这个,它在单击时显示和隐藏容器中的文本。我试图做的是,当我单击打开第一个隐藏文本,然后向下滚动以单击打开另一个隐藏文本时,我希望它滚动回该打开文本的同级图像以保持其在视图中。如何找到同级元素并在单击时滚动到它 这个是无效的Javascript 单击后滚动到同级元素,javascript,jquery,html,Javascript,Jquery,Html,请看一下这个,它在单击时显示和隐藏容器中的文本。我试图做的是,当我单击打开第一个隐藏文本,然后向下滚动以单击打开另一个隐藏文本时,我希望它滚动回该打开文本的同级图像以保持其在视图中。如何找到同级元素并在单击时滚动到它 这个是无效的 $('.slider2').click(function(e) { var imageposition = $(this).closest('.imageclass'); $(document.body).animate({scrollTop: ima
$('.slider2').click(function(e) {
var imageposition = $(this).closest('.imageclass');
$(document.body).animate({scrollTop: imageposition.offset().top}, 'fast');
});
HTML:
你至少有几个问题
$(this).closest('.imageclass')
不选择以前是
$(document.body)
滚动窗口(我自己对此表示怀疑)html,body
$(function () {
$('.slider2').click(function (e) {
e.preventDefault();
$(this).next(".internal").load($(this).data("ship"));
$('.internal').slideUp('normal');
var imageposition = $('.imageclass', $(this).closest('.container'));
if ($(this).next().is(':hidden') === true) {
$(this).addClass('on');
$(this).next().slideDown('normal', function () {
$('html, body').animate({scrollTop: $(imageposition).offset().top})
});
}
});
$('.internal').hide();
});
滚动功能的工作方式有点问题,因为active.container相对于其他容器的位置会发生变化(当处于活动和非活动状态时) 此外,不应查找最近的位置,而应查找其父元素 请看一下我的代码:CSS
.slider2 {
margin:40px;
}
.internal p {
padding:5px;
}
.internal h3 {
text-align:center;
}
.container {
position: relative;
}
您可能需要寻找一种方法来检测非活动容器的高度,因为我将我的容器作为静态值
JS:
$(function () {
$('.slider2').click(function (e) {
e.preventDefault();
$(this).next(".internal").load($(this).data("ship"));
$('.internal').slideUp('normal');
var imageposition = $('.imageclass', $(this).closest('.container'));
if ($(this).next().is(':hidden') === true) {
$(this).addClass('on');
$(this).next().slideDown('normal', function () {
$('html, body').animate({scrollTop: $(imageposition).offset().top})
});
}
});
$('.internal').hide();
});
.slider2 {
margin:40px;
}
.internal p {
padding:5px;
}
.internal h3 {
text-align:center;
}
.container {
position: relative;
}
$('.slider2').click(function (e) {
e.preventDefault();
$(this).next(".internal").load($(this).data("ship"));
var containerHeight = 205;
var containerIndex = $(this).offsetParent().index();
$('.internal').slideUp('normal');
if ($(this).next().is(':hidden') === true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
}
var scrollPosition = containerHeight * containerIndex;
$('body').animate({
scrollTop: scrollPosition
}, 'fast');
});
$('.internal').hide();