我有这个输入元素:
<input type="text" class="textfield" value="" id="subject" name="subject">
然后我还有一些其他元素,比如其他标签的&<textarea>标签等等。。。
当用户点击<input id=“#subject”>时,页面应该滚动到页面的最后一个元素,并且应该使用一个漂亮的动画(应该滚动到底部而不是顶部)。
页面的最后一项是带有#submit的提交按钮:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
动画不应该太快,应该是流畅的。
我正在运行最新的jQuery版本。我宁愿不安装任何插件,而是使用默认的jQuery特性来实现这一点。
非常简单且易于使用的自定义jQuery插件。只需将属性scroll=添加到可单击元素中,并将其值设置为要滚动到的选择器。
像这样:<a scroll=“#product”>单击我</a>。它可以用于任何元素。
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
假设您有一个带有id按钮的按钮,请尝试以下示例:
$("#button").click(function() {
$([document.documentElement, document.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><脚本>$(文档).ready(函数(){$(“#click”).click(函数(){$('html,body').animate({scrollTop:$(“#div1”).offset().top}, 2000);});});</script><div id=“div1”style=“height:1000px;width 100px”>测验</div><br/><div id=“div2”style=“height:1000px;width 100px”>测试2</div><button id=“click”>单击我</button></html>
当用户点击带有#subject的输入时,页面应该滚动到页面的最后一个元素并添加一个漂亮的动画。它应该是向下滚动而不是向上滚动。页面的最后一项是带有#submit的提交按钮
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
这将首先向下滚动到#submit,然后将光标恢复到单击的输入,这模拟向下滚动,适用于大多数浏览器。它也不需要jQuery,因为它可以用纯JavaScript编写。
通过链接焦点调用,这种使用焦点函数的方式可以更好地模拟动画吗。我还没有测试过这个理论,但它看起来像这样:
<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>
$('html,body').animate(…)在iPhone、Android、Chrome或Safari浏览器中不适用。
我必须以页面的根内容元素为目标。
$('#cotent').animate(…)
以下是我的结论:
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
所有正文内容都与#contentdiv连接
<html>
....
<body>
<div id="content">
...
</div>
</body>
</html>