javascript - 启用 "Terms and conditions"上的复选框滚动不起作用

标签 javascript jquery

我的复选框一开始就被选中,即使应该设置为false。每当我滚动时,复选框都会被选中,不会经过 if 语句。

https://jsfiddle.net/7mujuvn3/1/

$(document).ready(function () {
    //checkbox
    $('#box').attr('checked', 'false');
        $("#terms").scroll(function () {
            //the room for scrolling is 30px in the textarea
            if ($("#terms").scrollTop() === 30) {
                $('#box').attr('checked', 'true');
            } else {
                $('#box').attr('checked', 'false');
            }
        });
    });

最佳答案

您应该删除 truefalse 两边的引号,在所有情况下使用 prop,并在 scrollTop 之后使用括号code> 将其作为方法运行。另外,您可能需要使用 > 来检查 scrollTop,因为如果两者都大于或小于 30,它将取消选中该框再次。

https://jsfiddle.net/7mujuvn3/4/

$(document).ready(function () {
    //checkbox
    $('#box').prop('checked', false);

    $("#terms").scroll(function () {
        //the room for scrolling is 30px in the textarea
        if ($("#terms").scrollTop() > 30) {
            $('#box').prop('checked', true);
        } else {
            $('#box').prop('checked', false);
        }
    });
});
#terms {
    width: 300px;
    height: 180px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" id="terms" cols="30" rows="10">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquam aliquid
    at dignissimos doloribus explicabo suscipit vero! Aliquam beatae, cumque dignissimos eum expedita, in maxime neque optio quae quidem quos ut?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto aut blanditiis deserunt doloribus ea, eaque impedit laborum minima non officiis placeat quasi quidem repudiandae. At dolores explicabo inventore necessitatibus</textarea>
<input id="box" type="checkbox" checked="">

关于javascript - 启用 "Terms and conditions"上的复选框滚动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298186/

相关文章:

javascript - 如何从一副牌中随机选择一张牌并且不再选择它?

javascript - 在 JS 中,我可以仅 require() 模块的导出吗?

javascript - 在同一个 jquery 函数中,一行在前面的行之前执行

javascript - 单击时显示和隐藏 div

javascript - 选择单选按钮时隐藏特定的表单输入

javascript - 舍入<输入类型='color'>

javascript - 使用循环定义多个 JQuery 函数

javascript - 返回发行专辑最多的年份的函数

jquery - 如何在jquery ajax成功函数中解析以下json

jQuery - offset().left 为 float 元素提供了错误的值