我有一个大表与垂直滚动条。
我想使用jQuery/JavaScript滚动到这个表中的特定行。
是否有内置的方法来做到这一点?
Here is a little example to play with.
div {
width: 100px;
height: 70px;
border: 1px solid blue;
overflow: auto;
}
<div>
<table id="my_table">
<tr id='row_1'><td>1</td></tr>
<tr id='row_2'><td>2</td></tr>
<tr id='row_3'><td>3</td></tr>
<tr id='row_4'><td>4</td></tr>
<tr id='row_5'><td>5</td></tr>
<tr id='row_6'><td>6</td></tr>
<tr id='row_7'><td>7</td></tr>
<tr id='row_8'><td>8</td></tr>
<tr id='row_9'><td>9</td></tr>
</table>
</div>
为了它的价值,这就是我如何设法实现这种行为的一般元素,可以在一个DIV内滚动(不知道容器)
它会创建一个目标元素高度的伪输入,然后将焦点放在它上面,无论您在可滚动层次结构中有多深,浏览器都会关心其余的内容。效果非常好。
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');
$scrollTo.prepend(inputElem);
inputElem.css({
position: 'absolute',
width: '1px',
height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();
你可以通过jQuery和JavaScript滚动
只需要两个元素的jQuery和这个JavaScript代码:
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to-id").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 1500);
});
});
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to-id").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 1500);
});
});
#pane1 {
background: #000;
width: 400px;
height: 400px;
}
#pane2 {
background: #ff0000;
width: 400px;
height: 400px;
}
#pane3 {
background: #ccc;
width: 400px;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
<li>
<a href="#pane1" class=" js-scroll-to-id">Item 1</a>
</li>
<li>
<a href="#pane2" class="js-scroll-to-id">Item 2</a>
</li>
<li>
<a href="#pane3" class=" js-scroll-to-id">Item 3</a>
</li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
<a href="#pane3" class="js-scroll-to-id">Item 1</a>
</li>
<li>
<a href="#pane2" class="js-scroll-to-id">Item 2</a>
</li>
<li>
<a href="#pane1" class="js-scroll-to-id">Item 3</a>
</li>
</ul>