当用户点击表单时,我试图显示并隐藏表单,并尝试向下滚动以查看表单,我在第一次单击后使用的代码。如果我第一次点击它“显示表单但不向下滚动”第一次点击后工作正常。谁能解释一下我做错了什么。
$('#showForm').click(function()
{
$('.formL').toggle("slow");
$('.formL').get(0).scrollIntoView()
});
HTML:
<div class="formL" style="display: none">
<form action="">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
答案 0 :(得分:5)
问题在于,在该功能中,您尝试滚动到表单,但仍然不可见。要解决此问题,请在scrollIntoView()
函数的回调中调用toggle()
。请参阅此处的示例:https://jsfiddle.net/ux0qt5nn/
答案 1 :(得分:5)
问题是,在您第一次点击时,该元素尚未存在。将滚动功能放入回调中你就可以了。
$('#showForm').click(function(){
$('.formL').toggle("slow", function() {
$('.formL').get(0).scrollIntoView();
});
});
$('#showForm').click(function(){
$('.formL').toggle("slow", function() {
$('.formL').get(0).scrollIntoView()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="buttonForm" id="showForm"><span>Click here to see form</span></button>
<br><br><br><br><br><br><br><br><!--Extra lines to show scroll-->
<div class="formL" style="display: none">
<form action="">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</div>
答案 2 :(得分:2)
正如在其他答案中所解释的那样,您试图在元素可见之前以及在达到其实际高度之前将元素滚动到视图中。您可以使用以下方法滚动到显示表单所需的数量,并仍然让用户看到动画。请参阅代码中的注释。
$('#showForm').click(function() {
var formL = $('.formL').show(), // show the form wrapper in order to get its height
formLHeight = formL.height(),
formLForm = formL.find('form').hide(); // hide the form itself instead
formL.height(formLHeight);
formLForm.toggle("slow", function() {
// optionally, reset the height
formL.height('auto');
});
// this line is only needed so that the code snippet will not scroll the
// outer browser window, but only the iframe content. If you're not in an iframe,
// you can just use the original scrollIntoView() approach instead
document.documentElement.scrollTop = formL[0].offsetTop;
// formL.get(0).scrollIntoView();
});
#spacer {
background: red;
color: #fff;
height: 80vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="showForm">show form</button>
<div id="spacer">some long content</div>
<div class="formL" style="display: none">
<form action="">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</div>