我希望当我点击我的复选框时,它们应该被选中并自动向下滚动到下一个复选框问题。但是在下面的代码中,它在单击输入时向下滚动,但输入没有给出选中的结果。
点击复选框会向下滚动,但复选框未选中??
$(':checkbox').on('click', function() {
$(this).attr('checked', true, function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 500);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<form id="form-contents">
<div id="box1" class="box">
<div class="contents-box">
<label class="control-label " for="" style="font-family: 'Roboto', sans-serif; font-size: 20px;">Question1</label>
<br>
<label for="">
<input type="checkbox" href="#box2" name="checkbox1" >
option1
</label>
<br>
<label for="">
<input type="checkbox" href="#box2" name="checkbox2">
option2
</label>
<br>
<button class="scroll-link" href="#box2">Next</button>
</div>
</div>
<div id="box2" class="box">
<div class="contents-box">
<label class="control-label " for="" style="font-family: 'Roboto', sans-serif; font-size: 20px;">Question2</label>
<br>
<label for="">
<input type="checkbox" name="checkbox1" >
Good
</label>
<br>
<label for="">
<input type="checkbox" name="checkbox2">
Fine
</label>
<br>
<Br>
</div>
</div>
</form>
最佳答案
您试图在点击处理程序中做太多事情。单击复选框的自然效果是切换其选中状态;没有必要自己做。只需担心动画:
$(':checkbox').on('click', function() {
if (!$(this).attr('href')) return;
$('html').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 500);
});
label { display: block; } /* so you don't need all those <br>s */
.box { margin-bottom: 500px; } /* to force a scroll bar */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="box">
<h1>Question1</h1>
<label>
<input type="checkbox" href="#box2">
option1
</label>
<label>
<input type="checkbox" href="#box2">
option2
</label>
</div>
<div id="box2" class="box">
<h1>Question2</h1>
<label>
<input type="checkbox">
Good
</label>
<label>
<input type="checkbox">
Fine
</label>
</div>
如果无处可滚动,我还添加了一行以提早退出点击处理程序。它使您的控制台没有错误。
关于javascript - 在选中的收件箱上,它不会滚动到带有 id 框的下一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48067312/