gpt4 book ai didi

jQuery - 使 DIV 在浏览器上可见

转载 作者:行者123 更新时间:2023-12-01 02:01:53 24 4
gpt4 key购买 nike

我设计了一个大约两页的长表格。用户提交表单后,如果表单包含任何错误,我需要强制他/她查看表单顶部。

我的表单顶部有一个错误栏。

我的问题是如何让浏览器滚动到错误保持器以便用户可以轻松看到它?

谢谢

////////////////////////////////////////////关注 Peter 的评论

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">

// This is a functions that scrolls to the element with id id
function goToByScroll(id)
{
// Scroll
$('html,body').animate({
scrollTop: $(id).offset().top}, 'slow');
};

$(document).ready( function() {
debugger;
$('#clearhere').click(function() {
goToByScroll('topbar2');
});
});

</script>

</head>
<body>
<div id="topbar2">Hello world</div>

<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>
<div>DDDDDDDDDDDDDD</div>



<button type="button" id="clearhere" name="clearhere">Click Me!</button>
</body>
</html>

///////////////////////////////////////////////////////

最佳答案

要滚动到元素顶部,只需使用 jQuery .animate().offset()功能。例如,要滚动到具有作为参数传入的特定选择器(例如 id)的元素的顶部,use this :

  // This is a function that scrolls to the element that matches selector
function goToByScroll(selector){
// Scroll
$('html,body').animate({
scrollTop: $(selector).offset().top},
'slow');
};

例如,如果页面上只有一个表单,则可以使用:goToByScroll("form");。如果您想滚动到具有特定 id 的元素,请使用 goToByScroll("#myId"); ... 等等

如果要将滚动时间调整为精确的毫秒数,只需将 'slow' 替换为毫秒数,例如 1000(无引号)滚动 1 秒。

当您想滚动到表单顶部时,只需触发上述函数即可。

Here's a live jsFiddle example (as a 5 line jQuery plugin)

关于jQuery - 使 DIV 在浏览器上可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3490241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com