div()的scrollTop
是可视区域顶部内下多远。 div的height
是用户看到的数量。因此,div的scrollTop
加上div的height
必须至少与整个服务条款内部的总高度(我们称之为#termsInner
)一样多。
下面是一些例子HTML代码:(注:您可以在http://jsfiddle.net/8U7GY/6/尝试了这一点。)
<p id="instructions">Please read these terms and conditions now.
<b>You must scroll to the bottom before continuing.</b></p>
<div id="terms">
<div id="termsInner">
<p>Lorem ipsum...</p>
</div>
</div>
<span><a id="submit">Register me!</a></span>
一些CSS代码:
p {
padding: 0.25em;
}
#terms {
border: solid 1px;
height: 24em;
overflow: auto;
margin-bottom: 1em;
}
#termsInner {
padding: 0.5em 0;
}
.highlighted {
background-color: #ff0;
}
#submit {
color: blue;
text-decoration: underline;
}
和一些JavaScript代码:(必须在$(function() { ... }
);因此只有在文档准备好后才能执行。)
// Select the elements of the HTML page.
var instructions = $('#instructions'),
terms = $('#terms'),
termsInner = $('#termsInner'),
submit = $('#submit');
// Bind an event handler that will run when the user
// has not scrolled through the terms of service.
submit.bind('click', function() {
// Highlight the instructions.
instructions.addClass('highlighted');
// Remove the highlighting after two seconds.
setTimeout(function() {
instructions.removeClass('highlighted');
}, 2000);
});
// Once the user scrolls through, call showDialog instead
// when the user clicks.
terms.scroll(function() {
if (terms.scrollTop() + terms.height() >= termsInner.height()) {
submit.unbind('click').bind('click', showDialog);
}
});
// This is where you would continue the user registration process.
function showDialog() {
alert('whatever');
}
有几件重要的事情需要注意。
- 我们不使用
onclick
HTML属性,而是以编程方式使用bind
和unbind
绑定事件处理程序。这可以让我们根据用户是否滚动或不滚动来做出不同的事情。
- jQuery提供
scroll
方法来注册一个函数,以便在用户滚动div时运行。我们检查scrollTop
和height
的总和与div内的内容的高度,如果没有问题,我们解除绑定原来的处理器并绑定一个新处理器。
- 我们强调说明(如果用户还没有向下滚动,但仍然点击锚点)以便使用。如果用户点击并发现什么都没有发生,他会认为注册表不起作用,会离开您的网站,并留下不好的经历。
编辑:修复它在Internet Explorer上的工作。由于IE的工作方式,您不能在div #terms
本身设置填充,因此请在#termsInner
之间设置填充。
你能澄清“开/关”的功能?您是否打开/关闭用户到达ToA结尾后提交表单的能力? – shoebox639 2010-11-01 22:46:09
当用户点击锚时,它会运行showDialog(),我想只有当用户滚动到T&C的底部时才可以使用该选项。 – Xtian 2010-11-01 22:49:21