自动验证输入的邮箱地址是否正确,正确的才出现提交框,可以用在邮件订阅的位置
XML/HTML Code
- <form class="newsletter" autocomplete="off" novalidate>
- <input type="email" value="" placeholder="Enter your email address" tabindex="1" class="newsletter-email" />
- <input type="submit" value="OK" tabindex="2" class="newsletter-submit" />
- </form>
JavaScript Code
- <script>
- ;( function( window, document, undefined )
- {
- 'use strict';
- var form = '.newsletter',
- className = 'newsletter--active',
- email = 'input[type="email"]',
- addEventListener = function( element, event, handler )
- {
- element.addEventListener ? element.addEventListener( event, handler ) : element.attachEvent( 'on' + event, function(){ handler.call( element ); });
- },
- forEach = function( elements, fn )
- {
- for( var i = 0; i < elements.length; i++ ) fn( elements[ i ], i );
- },
- addClass = function( element, className )
- {
- element.classList ? element.classList.add( className ) : element.className += ' ' + className;
- },
- removeClass = function( element, className )
- {
- element.classList ? element.classList.remove( className ) : element.className += element.className.replace( new RegExp( '(^|\b)' + className.split( ' ' ).join( '|' ) + '(\b|$)', 'gi' ), ' ' );
- };
- forEach( document.querySelectorAll( form ), function( $form )
- {
- var $email = $form.querySelectorAll( email );
- if( $email.length )
- {
- $email = $email[ 0 ];
- addEventListener( $email, 'keyup', function()
- {
- $email.value != '' && /^([w-.]+@([w-]+.)+[w-]{2,12})?$/.test( $email.value ) ? addClass( $form, className ) : removeClass( $form, className );
- });
- }
- });
- })( window, document );
- /*
- jQuery version:
- $( function( $, window, document, undefined )
- {
- 'use strict';
- var form = '.newsletter',
- className = 'newsletter--active',
- email = 'input[type="email"]';
- $( form ).each( function()
- {
- var $form = $( this ),
- $email = $form.find( email );
- $email.on( 'keyup.addClassWhenEmail', function()
- {
- $form.toggleClass( className, $email.val() != '' && /^([w-.]+@([w-]+.)+[w-]{2,12})?$/.test( $email.val() ) );
- });
- });
- })( jQuery, window, document );
- */
- </script>
原文地址:http://www.freejs.net/article_biaodan_413.html