使用jQuery,如何强制访问者滚动到textarea的底部以启用提交按钮?
我有一个包含只读文本区域的注册表单。 我想要求任何访问者在提交按钮以提交其信息之前滚动到textarea的底部,其中包含条款和条件或许可协议。
这是示例CSS代码:
textarea { width: 240px; height: 200px; overflow-y: scroll; }
这是示例HTML代码:
是否已将disabled
属性放入提交输入中?
我们已经在使用jQuery库,所以我想继续使用jQuery来启用此validation来控制提交问题。 感谢您的帮助和建议!
像这样的东西应该工作:
$('#terms').scroll(function () { if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) { $('#register').removeAttr('disabled'); } });
只需给术语一个id,并在html中将注册按钮设置为禁用。 我也做了一个小小的小提示来展示它的工作: http : //jsfiddle.net/ETLZ8/
我建议这样做,它可以更好地处理缩放。
$('#terms').scroll(function () { if ($(this).scrollTop() + $(this).innerHeight() +2 >= $(this)[0].scrollHeight) { $('#register').removeAttr('disabled'); } });
当scrolltop + innerheight略低于scrollHeight时,+ 2处理一些缩放场景(出于某种原因,我太懒了,无法解决)。
Christian Varga的解决方案绝对正确,也可以应用于div。 但是,如果你使用div而不是textarea,div 必须没有任何填充或者它会中断。
我的解决方法是在我的样式div(带有填充,圆角和边框)中放置一个div来检测滚动。 所以:
Lorem ipsum...terms text...
这种方法唯一可能的缺点是如果你在包含div中添加填充,滚动条会出现在内部div上,这对某些用户来说可能看起来不太好。
其他答案工作得很完美,但我使用稍微不同的方法组合了一个示例 ,一个不能提交到被禁用的按钮的能力,以便它可以与其他validation器等混合。
$(function(){ var terms_were_scrolled = false; $('#terms').scroll(function () { if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) { terms_were_scrolled = true; } }); $('#terms_agreed').click(function( event ){ if( !terms_were_scrolled ){ alert('you must read all the way to the bottom before agreeing'); event.preventDefault(); } }); });
HTML:
在textarea中使用这样的东西:
onscroll="if(this.scrollTop+this.offsetHeight>=this.scrollHeight){/*enable the button*/}"
但是如果JS被禁用怎么办?
我更喜欢一个可滚动的div,底部有提交按钮。 无论JS是打开还是关闭,用户都无法在不滚动的情况下单击按钮。