[英]show/hide an overflow div on anchor
I'm trying to make a div appear (if not already visible) and be scrolled to a specific anchor. 我正在尝试使div显示(如果尚未显示)并滚动到特定锚点。 I found this answer and try to use it but it looks like it doesn't work well... 我找到了这个答案并尝试使用它,但看起来效果不好......
https://stackoverflow.com/a/7513110/3703099 https://stackoverflow.com/a/7513110/3703099
My code : http://jsfiddle.net/0sq2rfcx/9/ 我的代码: http : //jsfiddle.net/0sq2rfcx/9/
As you can see, when you click on button it scroll to the anchor, but if you click again, it scroll to an other position... I would like to make it stay on the current anchor if you keep clicking the button. 正如您所看到的,当您单击按钮时,它会滚动到锚点,但是如果再次单击,它会滚动到另一个位置...如果您一直单击按钮,我希望它保持在当前锚点上。
Can you help me to find what I did wrong plz ? 你能帮我找一下我做错的事吗?
$('#b1').click(function() { $('#result').show(); $('#result').scrollTop($('#a1').offset().top); }); $('#b2').click(function() { $('#result').show(); $('#result').scrollTop($('#a2').offset().top); }); $('#b3').click(function() { $('#result').show(); $('#result').scrollTop($('#a3').offset().top); });
#result { display: none; height: 200px; overflow-y: auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id='b1'>b1</button> <button id='b2'>b2</button> <button id='b3'>b3</button> <button onclick="$('#result').hide();">hide</button> <div id='result'> <p>bla 0</p> <br/> <br/> <br/> <br/> <br/> <p id='a1'>bla 1</p> <br/> <br/> <br/> <br/> <br/> <p id='a2'>bla 2</p> <br/> <br/> <br/> <br/> <br/> <p id='a3'>bla 3</p> <br/> <br/> <br/> <br/> <br/> </div>
I've just updated your jsfiddle: http://jsfiddle.net/0sq2rfcx/8/ 我刚刚更新了你的jsfiddle: http : //jsfiddle.net/0sq2rfcx/8/
This should work on all browsers included IE7
$('#b1').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a1').parent().scrollTop() + $('#a1').offset().top - $('#a1').parent().offset().top}, "slow");
});
$('#b2').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a2').parent().scrollTop() + $('#a2').offset().top - $('#a2').parent().offset().top}, "slow");
});
$('#b3').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a3').parent().scrollTop() + $('#a3').offset().top - $('#a3').parent().offset().top}, "slow");
You can use position instead to scroll
like one below: 您可以使用位置来scroll
如下所示:
$('#b1').click(function () {
$('#result').show();
$('#result').animate({
'scrollTop' : $("#a1").position().top-10 //-10 here is just to set it in view!!
});
});
Added animation
for smoothness 添加animation
以获得平滑度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.