(4)事件处理——(8)一个简单的风格切换器(A simple style switcher)
To illustrate some event handling techniques, suppose we wish to have a single page rendered in several different styles based on user input. We will allow the user to click buttons to toggle between a normal view, a view in which the text is constrained to a narrow column, and a view with large print for the content area.
Progressive enhancement
In a real-world example, a good web citizen will employ the principle of progressive enhancementhere. The style switcher should either be hidden when JavaScript is unavailable or, better yet, should still function through links to alternative versions of the page. For the purposes of this tutorial, we'll assume that all users have JavaScript turned on.
渐进增强
<div id="switcher" class="switcher"> <h3>Style Switcher</h3> <button id="switcher-default"> Default </button> <button id="switcher-narrow"> Narrow Column </button> <button id="switcher-large"> Large Print </button> </div>
<div id="switcher" class="switcher"> <h3>Style Switcher</h3> <button id="switcher-default"> Default </button> <button id="switcher-narrow"> Narrow Column </button> <button id="switcher-large"> Large Print </button> </div>Combined with the rest of the page's HTML markup and some basic CSS, we get a page that looks like the following screenshot:
$('body').addClass('large');
$(document).ready(function() { $('#switcher-large').bind('click', function() { $('body').addClass('large'); }); });然而,我们想要这个在按钮被点击的时候发生,而不是像我们现在看到的那样在网页被加载的时候发生。为了做到这点,我们引入了.bind()函数。这个方法允许我们特殊化DOM事件,然后在上面绑定行为。在这种场景下,事件应该是click,行为应该是由我们之前的一行代码组成的函数:
$(document).ready(function() { $('#switcher-large').bind('click', function() { $('body').addClass('large'); }); });Now when the button gets clicked, our code runs, and the text is enlarged, as shown in the following screenshot:
This is not necessarily the most elegant or efficient way to accomplish this task. As we proceed through this chapter, we will extend and refine this code into something we can be proud of.