未捕获文本区域滚动事件



我有一个包含条款和条件的textarea,它是可滚动的。当我向下滚动textarea时,我想启用一个复选框,用户可以选中并继续。问题是它不起作用。

<textarea name="terms" runat="server" id="terms" style="resize:none" disabled="disabled" rows="20" cols="10">
<asp:CheckBox ID="chk_termos" runat="server" Enabled="false" AutoPostBack="true"/>
<script type="text/javascript">
  $(document).ready(function() {
    $("#terms").scroll(function() {
      alert("AI O CARALHO")
      if ($("#terms").scrollTop() > 10) {
        $('#chk_termos').prop('disabled', true);
      } else {
        $('#chk_termos').prop('disabled', false);
      }
    });
  });
</script>

当我甚至滚动以获取alert("AI O CARALHO")时,它只是没有显示,所以我想该功能甚至不起作用。

您已将

textarea设置为禁用,这将禁用其中的所有功能。

相反,根本不要使用textarea,而只使用 div 元素,因为它们首先是默认不可编辑的。您还在if分支中反转了启用/禁用的命令。

$(function () {
  $("#terms").scroll(function () {
     //alert("AI O CARALHO")
     if ($("#terms").scrollTop() > 10) {
        $('#chk_termos').removeAttr('disabled');
     } else {
        $('#chk_termos').attr('disabled', 'disabled');
    }
  });
});
#terms { height: 5em; overflow-y:scroll; width:25%; border:1px solid #e0e0e0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="terms">
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
 Read all of this and scroll to the bottom<br>
</div>
<input type="checkbox" id="chk_termos" disabled="disabled">

您的代码只能在 Chrome 中使用。在所有其他浏览器中disabled表单元素不会引发scroll事件,因此您的逻辑永远不会触发。

要解决此问题,您可以改用readonly,以便用户无法修改textarea的内容,但它仍然根据需要触发scroll事件:

$(document).ready(function() {
  $("#terms").scroll(function() {
    $('#chk_termos').prop('disabled', $(this).scrollTop() > 10);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="terms" id="terms" style="resize:none" readonly="true" rows="20" cols="10">
Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. Lorem ipsum dolor sita amet consectetur adipscing elit. 
</textarea>
<input type="checkbox" id="chk_termos" name="chk_thermos" />

最新更新