如何通过JQuery将DIV的滚动条滚动到指定的位置
1个回答
展开全部
使用jquery的scrollTop函数进行滚动控制:
举个栗子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="author" content="sleest">
<meta name="description" content="2017/08/07 jQuery scrollTop example" />
<title>Document</title>
</head>
<body>
<div style="background: #bdbdbd;height:400px;width:300px;overflow:auto;" id="container">
<div id="content-1" style="height: 200px;background-color:#03a9f4;color:#fff">Height.200px</div>
<div id="content-2" style="height: 300px;background-color:#ffc107;color:#fff">Height.300px</div>
<div id="content-3" style="height: 150px;background-color:#E91E63;color:#fff">Height.150px</div>
</div>
<div style="margin-top:20px">
<label>Pixel Scroll:</label>
<input type="number" value="0" id="scrollPixel" step="50" />
<button type="button" id="btn-scroll-to">Scroll</button>
</div>
<div style="margin-top:20px">
<label>Element Scroll:</label>
<select id="scrollElement">
<option value="" selected>-- choose element 2 scorll</option>
<option value="#content-1">Content1, Height 200px</option>
<option value="#content-2">Content2, Height 300px</option>
<option value="#content-3">Content3, Height 150px</option>
</select>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
+(function($) {
var $scrollPixel = $('#scrollPixel'),
$container = $('#container');
function scrollPixel() {
$container.scrollTop(+$scrollPixel.val());
}
function scrollElement() {
var $t = $(this),
elId = $t.val();
if (elId) $container.scrollTop($(elId)[0].offsetTop - $container[0].offsetTop);
}
$(function() {
$('#btn-scroll-to').bind('click', scrollPixel)
$('#scrollElement').bind('change', scrollElement)
})
})(jQuery);
</script>
</body>
</html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询