javascript - js页面滚动到指定位置 - 原生js滚动到指定位置
jQuery滚动到元素 (16)
我有这个input
元素:
<input type="text" class="textfield" value="" id="subject" name="subject">
然后我还有一些其他元素,如其他文本输入,textareas等。
当用户用#subject
单击该input
时,页面应该以良好的动画滚动到页面的最后一个元素。 它应该是一个滚动到底部而不是顶部。
该页面的最后一个项目是一个submit
按钮,其中包含#submit
:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
动画不应该太快,应该是流畅的。
我正在运行最新的jQuery版本。 我更喜欢不安装任何插件,而是使用默认的jQuery功能来实现此目的。
当用户用#subject单击该输入时,页面应该以良好的动画滚动到页面的最后一个元素。 它应该是一个滚动到底部而不是顶部。
该页面的最后一项是一个带#submit的提交按钮
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
这将首先向下滚动到#submit
然后将光标恢复到被单击的输入,该输入模仿向下滚动,并适用于大多数浏览器。 它也不需要jQuery,因为它可以用纯JavaScript编写。
通过链接focus
调用,这种使用focus
功能的方式能够以更好的方式模拟动画。 我没有测试过这个理论,但它看起来像这样:
<style>
#F > *
{
width: 100%;
}
</style>
<form id="F" >
<div id="child_1"> .. </div>
<div id="child_2"> .. </div>
..
<div id="child_K"> .. </div>
</form>
<script>
$('#child_N').click(function()
{
$('#child_N').focus();
$('#child_N+1').focus();
..
$('#child_K').focus();
$('#child_N').focus();
});
</script>
Steve和Peter的解决方案非常好。
但在某些情况下,您可能必须将该值转换为整数。 奇怪的是,从$("...").offset().top
返回的值有时是float
。
使用: parseInt($("....").offset().top)
例如:
$("#button").click(function() {
$('html, body').animate({
scrollTop: parseInt($("#elementtoScrollToID").offset().top)
}, 2000);
});
$('html, body').animate(...)
不适合iphone,android chrome Safari浏览器。
我必须定位页面的根内容元素。
$( '#cotnent')。动画(...)
这是我结束了
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
所有身体内容都与#content div联系起来
<html>
....
<body>
<div id="content">
....
</div>
</body>
</html>
使用此解决方案,您不需要任何插件,除了在关闭</body>
标签之前放置脚本之外,不需要任何安装程序 。
$("a[href^='#']").on("click", function(e) {
e.preventDefault();
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
在加载时,如果地址中存在散列,我们将滚动到该地址。
而且 - 无论何时您点击带有href
散列a
链接(例如#top
,我们都会滚动到该链接。
假设你有一个带有id button
,试试这个例子:
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
我从文章中得到了代码顺利滚动到没有jQuery插件的元素 。 我已经在下面的例子中对它进行了测试。
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
动画:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
如果你想在一个溢出容器中滚动(而不是上面的$('html, body')
),也可以使用绝对定位,这是一种方法:
var elem = $('#myElement'),
container = $('#myScrollableContainer'),
pos = elem.position().top + container.scrollTop() - container.position().top;
container.animate({
scrollTop: pos
}
如果您只处理滚动到输入元素,则可以使用focus()
。 例如,如果您想滚动到第一个可见输入:
$(':input:visible').first().focus();
或者类的.error
容器中的第一个可见输入:
$('.error :input:visible').first().focus();
感谢Tricia Ball指出了这一点!
对于它的价值,这是我如何设法实现这种行为的一般元素,可以在DIV内滚动。 在我们的例子中,我们不会滚动整个主体,而只是特定的具有溢出的元素:auto; 在一个更大的布局。
它会创建目标元素高度的假输入,然后将焦点放在该元素上,并且无论您在可滚动层次结构中有多深,浏览器都会关心其余部分。 奇迹般有效。
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对象,CSS选择器或数值。
用法示例:
// scroll to "#target-element":
$.scrollTo("#target-element");
// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);
// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
该函数的代码:
/**
* Scrolls the container to the target position minus the offset
*
* @param target - the destination to scroll to, can be a jQuery object
* jQuery selector, or numeric position
* @param offset - the offset in pixels from the target position, e.g.
* pass -80 to scroll to 80 pixels above the target
* @param speed - the scroll speed in milliseconds, or one of the
* strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
* be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {
if (isNaN(target)) {
if (!(target instanceof jQuery))
target = $(target);
target = parseInt(target.offset().top);
}
container = container || "html, body";
if (!(container instanceof jQuery))
container = $(container);
speed = speed || 500;
offset = offset || 0;
container.animate({
scrollTop: target + offset
}, speed);
};
查看ScrollTo插件。 你可以在看到演示。
我希望它有帮助。
简单的方法来实现页面的滚动目标div ID
var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
要显示完整元素(如果可以使用当前窗口大小):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
这是我使用泛型类选择器抽象ID和href的方法
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to").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
}, 500);
});
});
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
<a href="#section-1" class="nav-item js-scroll-to">Item 1</a>
</li>
<li>
<a href="#section-2" class="nav-item js-scroll-to">Item 2</a>
</li>
<li>
<a href="#section-3" class="nav-item js-scroll-to">Item 3</a>
</li>
</ul>
jQuery(document).ready(function($) {
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate( {
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
} );
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul role="tablist">
<li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
<li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
<li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
$('html, body').animate({scrollTop:
Math.min(
$(to).offset().top-margintop, //margintop is the margin above the target
$('body')[0].scrollHeight-$('body').height()) //if the target is at the bottom
}, 2000);