60款很酷的 jQuery 幻灯片演示和下载

最后更新于:2022-04-01 10:05:29

[转自:http://www.cnblogs.com/lhb25/archive/2011/05/31/2056103.html](http://www.cnblogs.com/lhb25/category/277997.html) [jQuery](http://www.cnblogs.com/lhb25/category/277997.html) 是一个非常优秀的[JavaScript](http://www.cnblogs.com/lhb25/category/146074.html) 框架,使用简单灵活,同时还有许多成熟的插件可供选择,它可以帮助你在项目中加入漂亮的效果,其中之一就是幻灯片效果的实现,这是一种在有限的网页空间内展示系列项目时非常好的方法。 今天这篇文章要给大家分享的是60款很酷的 [jQuery](http://www.cnblogs.com/lhb25/category/277997.html) 幻灯片插件,相信里面一定会有你喜欢的。 [Cloud Carousel](http://www.professorcloud.com/mainsite/carousel.htm) ([演示](http://www.professorcloud.com/mainsite/carousel.htm) |[下载](http://www.professorcloud.com/downloads/cloud-carousel.1.0.5.zip)) [![Jqueryimage481 in Cool and Useful jQuery Image and Content Sliders and Slideshows](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da9d252.jpg)](http://www.professorcloud.com/mainsite/carousel.htm) [ShineTime](http://addyosmani.com/blog/shinetime/) ([演示](http://www.addyosmani.com/resources/shinetime/) |[下载](http://www.addyosmani.com/resources/shinetime/shinetime.1.01.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dabb42b.jpg)](http://addyosmani.com/blog/shinetime/) [Nivo Slider](http://nivo.dev7studios.com/) ([演示](http://nivo.dev7studios.com/demos/) |[下载](http://dev7studios.com/downloads/31)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dad5a05.jpg)](http://nivo.dev7studios.com/) [Interactive Photo Desk](http://tympanus.net/codrops/2010/07/01/interactive-photo-desk/) ([演示](http://tympanus.net/Development/PhotoDesk/) |[下载](http://tympanus.net/Development/PhotoDesk/PhotoDesk.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252daefc6e.jpg)](http://tympanus.net/codrops/2010/07/01/interactive-photo-desk/) [Beautiful Photo Stack Gallery with jQuery and CSS3](http://tympanus.net/codrops/2010/06/27/beautiful-photo-stack-gallery-with-jquery-and-css3/) ([演示](http://tympanus.net/Tutorials/PhotoStack/) | [下载](http://tympanus.net/Tutorials/PhotoStack/PhotoStack.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db181e6.jpg)](http://tympanus.net/codrops/2010/06/27/beautiful-photo-stack-gallery-with-jquery-and-css3/) [Micro Image Gallery: A jQuery Plugin](http://tympanus.net/codrops/2010/04/19/micro-image-gallery-a-jquery-plugin-2/) ([演示](http://tympanus.net/Tutorials/MicroGallery/) | [下载](http://tympanus.net/Tutorials/MicroGallery/MicroGallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db30e33.jpg)](http://tympanus.net/codrops/2010/04/19/micro-image-gallery-a-jquery-plugin-2/) [Minimalistic Slideshow Gallery with jQuery](http://tympanus.net/codrops/2010/07/05/minimalistic-slideshow-gallery/) ([演示](http://tympanus.net/Tutorials/MinimalisticSlideshowGallery/) | [下载](http://tympanus.net/Tutorials/MinimalisticSlideshowGallery/MinimalisticSlideshowGallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db426a7.jpg)](http://tympanus.net/codrops/2010/07/05/minimalistic-slideshow-gallery/) [Image Slider with Unique Effects](http://workshop.rs/2010/04/coin-slider-image-slider-with-unique-effects/) ([演示](http://workshop.rs/projects/coin-slider) |[下载](https://code.google.com/p/coin-slider/downloads/list)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db5d667.jpg)](http://workshop.rs/2010/04/coin-slider-image-slider-with-unique-effects/) [Create image gallery in 4 lines of jQuery](http://workshop.rs/2010/07/create-image-gallery-in-4-lines-of-jquery/) ([演示](http://workshop.rs/demo/gallery-in-4-lines) |[下载](http://workshop.rs/demo/gallery-in-4-lines/gallery-in-4-lines.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db7f8f1.jpg)](http://workshop.rs/2010/07/create-image-gallery-in-4-lines-of-jquery/) [Slideshow with strip effects](http://workshop.rs/projects/jqfancytransitions/) ([演示](http://workshop.rs/projects/jqfancytransitions/) |[下载](http://workshop.rs/2009/12/image-gallery-with-fancy-transitions-effects/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252db9af9d.jpg)](http://workshop.rs/projects/jqfancytransitions/) [Nivo Zoom](http://dev7studios.com/portfolio/nivo-zoom/)([演示](http://nivozoom.dev7studios.com/) |[下载](http://dev7studios.com/downloads/24)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dbb5a83.jpg)](http://dev7studios.com/portfolio/nivo-zoom/) [AD Gallery, gallery plugin for jQuery](http://coffeescripter.com/code/ad-gallery/) ([演示](http://coffeescripter.com/code/ad-gallery/) |[下载](http://coffeescripter.com/code/ad-gallery/jquery.ad-gallery.1.2.4.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc03bf4.jpg)](http://coffeescripter.com/code/ad-gallery/) [MLB.com Content Switcher with jQuery and CSS3](http://www.impressivewebs.com/mlb-switcher/) ([演示](http://www.impressivewebs.com/demo-files/mlb-switcher/#1) |[下载](http://www.impressivewebs.com/demo-files/mlb-switcher/mlb-switcher-code.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc1eb8e.jpg)](http://www.impressivewebs.com/mlb-switcher/) [Create Scrollable Interface](http://www.viget.com/inspire/jquery-image-scroller-plugin/) ([演示](http://www.viget.com/uploads/file/image-scroller/) |[下载](http://www.viget.com/inspire/jquery-image-scroller-plugin/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc39a7c.jpg)](http://www.viget.com/inspire/jquery-image-scroller-plugin/) [Animate Panning Slideshow with jQuery](http://buildinternet.com/2010/02/animate-panning-slideshow-with-jquery/) ([演示](http://s3.amazonaws.com/buildinternet/live-tutorials/panning-slideshow/panning-slideshow.htm) | [下载](http://s3.amazonaws.com/buildinternet/live-tutorials/panning-slideshow/panning-slideshow.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc535ef.jpg)](http://buildinternet.com/2010/02/animate-panning-slideshow-with-jquery/) [Image Scale Carousel](http://johnpatrickgiven.com/jquery/Image-Scale-Carousel/) ([演示](http://johnpatrickgiven.com/jquery/Image-Scale-Carousel/) |[下载](http://johnpatrickgiven.com/jquery/Image-Scale-Carousel/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc685e0.jpg)](http://johnpatrickgiven.com/jquery/Image-Scale-Carousel/) [Sudo Slider](http://webbies.dk/Sudo%20Slider/basic.html) ([演示](http://webbies.dk/Sudo%20Slider/) |[下载](http://webbies.dk/Sudo%20Slider/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc866a8.jpg)](http://webbies.dk/Sudo%20Slider/basic.html) [GALLERYVIEW](http://plugins.jquery.com/project/galleryview/) ([演示](http://spaceforaname.com/gallery-light.html) |[下载](http://plugins.jquery.com/files/galleryview-2.1.1.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dc9c19a.jpg)](http://plugins.jquery.com/project/galleryview/) [Jquery Plugin MopSlider 2.4](http://www.mopstudio.jp/mopSlider2descrip.html) ([演示](http://www.mopstudio.jp/mopSlider2demo.html) |[下载](http://www.mopstudio.jp/mopPlugin/mopSlider.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dcbad2c.jpg)](http://www.mopstudio.jp/mopSlider2descrip.html) [jQuery Image Scroller](http://net.tutsplus.com/tutorials/javascript-ajax/building-a-jquery-image-scroller/) ([演示](http://cdn.net.tutsplus.com/300_jquery/image%20Scroller/imageScroller.html) | [下载](http://cdn.net.tutsplus.com/300_jquery/image%20Scroller.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dcce0d1.jpg)](http://net.tutsplus.com/tutorials/javascript-ajax/building-a-jquery-image-scroller/) [Image Gallery Using jQuery and Flickr](http://galleria.aino.se/) ([演示](http://galleria.aino.se/) |[下载](http://galleria.aino.se/media/galleria/demos/fullscreen-03.html)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dce4e32.jpg)](http://galleria.aino.se/) [jQuery plugin: Wilq32.RotateImage](http://wilq32.adobeair.pl/jQueryRotate/Wilq32.jQueryRotate.html) ([演示](http://wilq32.adobeair.pl/jQueryRotate/Wilq32.jQueryRotate.html) | [下载](http://wilq32.adobeair.pl/jQueryRotate/Wilq32.jQueryRotate.html)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dd08d14.jpg)](http://wilq32.adobeair.pl/jQueryRotate/Wilq32.jQueryRotate.html) [jQZoom Evolution](http://www.mind-projects.it/projects/jqzoom/) ([演示](http://www.mind-projects.it/projects/jqzoom/demos.php#demo1) |[下载](http://www.mind-projects.it/projects/jqzoom/archives/jqzoom_ev1.0.1.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dd21079.jpg)](http://www.mind-projects.it/projects/jqzoom/) [Photo gallery using jQuery and VisualLightBox](http://www.script-tutorials.com/creating-photo-gallery-using-jquery-and-visuallightbox/) ([演示](http://www.script-tutorials.com/demos/11/index.html) | [下载](http://www.script-tutorials.com/demos/11/source.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dd365bf.jpg)](http://www.script-tutorials.com/creating-photo-gallery-using-jquery-and-visuallightbox/) [Zoomimage](http://www.script-tutorials.com/jquery-css-tutorial-zooming-image/) ([演示](http://www.script-tutorials.com/demos/3/source.html) |[下载](http://www.script-tutorials.com/demos/3/source.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dd5234c.jpg)](http://www.script-tutorials.com/jquery-css-tutorial-zooming-image/) [YoxView](http://www.yoxigen.com/yoxview/Default.aspx) ([演示](http://www.yoxigen.com/yoxview/Default.aspx) |[下载](http://www.yoxigen.com/yoxview/download.aspx)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dd7e9ea.jpg)](http://www.yoxigen.com/yoxview/Default.aspx) [Supersized](http://buildinternet.com/2009/05/supersized-20-full-screen-imagebackground-slideshow-jquery-plugin-w-transitions-and-controls/) ([演示](http://www.buildinternet.com/project/supersized/default.php) | [下载](http://buildinternet.com/project/supersized/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dda9793.jpg)](http://buildinternet.com/2009/05/supersized-20-full-screen-imagebackground-slideshow-jquery-plugin-w-transitions-and-controls/) [AnythingSlider](http://css-tricks.com/examples/AnythingSlider/#panel-4) ([演示](http://css-tricks.com/examples/AnythingSlider/#panel-3) |[下载](http://github.com/chriscoyier/AnythingSlider/archives/master)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252ddc20a2.jpg)](http://css-tricks.com/examples/AnythingSlider/#panel-4) [Photo Revealer](http://css-tricks.com/examples/RevealingPhotoSlider2/) ([演示](http://css-tricks.com/examples/RevealingPhotoSlider2/) |[下载](http://css-tricks.com/examples/RevealingPhotoSlider.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dddb8fc.jpg)](http://css-tricks.com/examples/RevealingPhotoSlider2/) [Exposure](http://plugins.jquery.com/project/Exposure) ([演示](http://plugins.jquery.com/project/Exposure) |[下载](http://plugins.jquery.com/project/Exposure)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252ddf274d.jpg)](http://plugins.jquery.com/project/Exposure) [Auto-Playing Featured Content Slider](http://css-tricks.com/creating-a-slick-auto-playing-featured-content-slider/) ([演示](http://css-tricks.com/examples/FeaturedContentSlider/) | [下载](http://css-tricks.com/examples/FeaturedContentSlider.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de188c6.jpg)](http://css-tricks.com/creating-a-slick-auto-playing-featured-content-slider/) [Horinaja](http://www.davidmassiani.com/horinaja/) ([演示](http://www.davidmassiani.com/horinaja/) |[下载](http://www.davidmassiani.com/horinaja/download.php)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de2f6dc.jpg)](http://www.davidmassiani.com/horinaja/) [S3 Slider](http://www.serie3.info/s3slider/demonstration.html) ([演示](http://www.serie3.info/s3slider/demonstration.html) |[下载](http://www.serie3.info/s3slider/demonstration.html)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de4448d.jpg)](http://www.serie3.info/s3slider/demonstration.html) [Slide Deck](http://www.slidedeck.com/) ([演示](http://www.slidedeck.com/) |[下载](http://www.slidedeck.com/pricing/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de59555.jpg)](http://www.slidedeck.com/) [Galleriffic](http://www.twospy.com/galleriffic/index.html) ([演示](http://www.twospy.com/galleriffic/example-2.html) |[下载](http://www.twospy.com/galleriffic/galleriffic-2.0.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de708e5.jpg)](http://www.twospy.com/galleriffic/index.html) [Photo Gallery – Dark Theme](http://spaceforaname.com/gallery-dark.html) ([演示](http://spaceforaname.com/gallery-dark.html) |[下载](http://spaceforaname.com/gallery-dark.html)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252de8b356.jpg)](http://spaceforaname.com/gallery-dark.html) [jQuery morphing gallery](http://codeassembly.com/jQuery-morphing-gallery/) ([演示](http://codeassembly.com/examples/gallery/index.html#next) |[下载](http://codeassembly.com/files/gallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252deb1343.jpg)](http://codeassembly.com/jQuery-morphing-gallery/) [Simple Accordion w/ CSS and jQuery](http://www.sohtanaka.com/web-design/examples/accordion/) ([演示](http://www.sohtanaka.com/web-design/examples/accordion/) |[下载](http://www.sohtanaka.com/web-design/simple-accordion-w-css-and-jquery/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252deca54c.jpg)](http://www.sohtanaka.com/web-design/examples/accordion/) [Automatic Image Slider w/ CSS & jQuery](http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery/) ([演示](http://www.sohtanaka.com/web-design/examples/image-slider/) | [下载](http://www.sohtanaka.com/web-design/examples/image-slider/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dee27ba.jpg)](http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery/) [Create a Slick and Accessible Slideshow Using jQuery](http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/) ([演示](http://sixrevisions.com/demo/slideshow/final.html) | [下载](http://downloads.sixrevisions.com/slick_accessible_slideshow.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df01570.jpg)](http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/) [Fancy Thumbnail Hover Effect w/ jQuery](http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/) ([演示](http://www.sohtanaka.com/web-design/examples/image-zoom/) | [下载](http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df184a1.jpg)](http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/) [Coda Slider Effect](http://jqueryfordesigners.com/coda-slider-effect/) ([演示](http://jqueryfordesigners.com/coda-slider-effect/) |[下载](http://jqueryfordesigners.com/coda-slider-effect/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df2f534.jpg)](http://jqueryfordesigners.com/coda-slider-effect/) [Simple Controls Gallery](http://www.dynamicdrive.com/dynamicindex4/simplegallery.htm) ([演示](http://www.dynamicdrive.com/dynamicindex4/simplegallery.htm) |[下载](http://www.dynamicdrive.com/dynamicindex4/simplegallery.htm)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df4a61c.jpg)](http://www.dynamicdrive.com/dynamicindex4/simplegallery.htm) [Popeye](http://dev.herr-schuessler.de/jquery/popeye/index.html) ([演示](http://dev.herr-schuessler.de/jquery/popeye/demo.html) |[下载](http://plugins.jquery.com/project/popeye)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df69db6.jpg)](http://dev.herr-schuessler.de/jquery/popeye/index.html) [Simple 演示](http://www.maaki.com/thomas/SmoothDivScroll/#quickdemo) ([演示](http://www.maaki.com/thomas/SmoothDivScroll/#quickdemo) |[下载](http://www.maaki.com/thomas/SmoothDivScroll/download/SmoothDivScroll-1.0.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252df84d8c.jpg)](http://www.maaki.com/thomas/SmoothDivScroll/#quickdemo) [ImageFlow](http://imageflow.finnrudolph.de/) ([演示](http://imageflow.finnrudolph.de/) |[下载](http://finnrudolph.de/ImageFlow/Download)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dfa31f0.jpg)](http://imageflow.finnrudolph.de/) [Moving Boxes](http://css-tricks.com/moving-boxes/) ([演示](http://css-tricks.com/examples/MovingBoxes/) |[下载](http://github.com/chriscoyier/MovingBoxes)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dfb8ebf.jpg)](http://css-tricks.com/moving-boxes/) [SlideViewerPro](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/svwt/index.html)([演示](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/svwt/index.html) |[下载](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/svwt/index.html)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dfcbf2f.jpg)](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/svwt/index.html) [Pirobox](http://www.pirolab.it/pirobox/index.php#demos) ([演示](http://www.pirolab.it/pirobox/index.php#demos) |[下载](http://www.pirolab.it/pirobox/index.php#demos)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252dfeb00d.jpg)](http://www.pirolab.it/pirobox/index.php#demos) [jQuery simple panorama viewer](http://www.openstudio.fr/jquery.panorama/) ([演示](http://www.openstudio.fr/jquery.panorama/) |[下载](http://www.openstudio.fr/download/jquery.panorama.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e011d4d.jpg)](http://www.openstudio.fr/jquery.panorama/) [A Beautiful Apple-style Slideshow Gallery](http://tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/) ([演示](http://demo.tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/demo.html) | [下载](http://demo.tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/demo.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0342e7.jpg)](http://tutorialzine.com/2009/11/beautiful-apple-gallery-slideshow/) [Flickr Photobar Gallery](http://tympanus.net/codrops/2010/06/10/flickr-photobar-gallery/) ([演示](http://tympanus.net/Tutorials/FlickrPhotobarGallery/) |[下载](http://tympanus.net/Tutorials/FlickrPhotobarGallery/FlickrPhotobarGallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0495bd.jpg)](http://tympanus.net/codrops/2010/06/10/flickr-photobar-gallery/) [Step Carousel Viewer](http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm) ([演示](http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm) |[下载](http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e05c0a8.jpg)](http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm) [Zoom-Info](http://addyosmani.com/blog/zoom-info-how-to-create-an-informative-image-gallery-with-jquery-css/) ([演示](http://addyosmani.com/resources/zoominfo/index.html) | [下载](http://addyosmani.com/resources/zoominfo/zoom-info.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0726ce.jpg)](http://addyosmani.com/blog/zoom-info-how-to-create-an-informative-image-gallery-with-jquery-css/) [Box Slider](http://nv.github.com/box-slider/) ([演示](http://nv.github.com/box-slider/) |[下载](http://nv.github.com/box-slider/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e08ff96.jpg)](http://nv.github.com/box-slider/) [jQuery Panel Gallery](http://www.catchmyfame.com/2009/05/02/jquery-panel-gallery-plugin/) ([演示](http://www.catchmyfame.com/jquery/demo/2/) |[下载](http://www.catchmyfame.com/2009/05/02/jquery-panel-gallery-plugin/)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0b1925.jpg)](http://www.catchmyfame.com/2009/05/02/jquery-panel-gallery-plugin/) [Image Highlighting and Preview with jQuery](http://tympanus.net/codrops/2010/07/04/image-highlighting-preview/) ([演示](http://tympanus.net/Tutorials/ImageHighlighter/) | [下载](http://tympanus.net/Tutorials/ImageHighlighter/ImageHighlighter.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0ccafb.jpg)](http://tympanus.net/codrops/2010/07/04/image-highlighting-preview/) [Multimedia Gallery for Images, Video and Audio](http://tympanus.net/codrops/2010/06/24/multimedia-gallery/) ([演示](http://tympanus.net/Development/MultiMediaGallery/) |[下载](http://tympanus.net/Development/MultiMediaGallery/MultiMediaGallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e0eb063.jpg)](http://tympanus.net/codrops/2010/06/24/multimedia-gallery/) [Awesome Mobile Image Gallery Web App](http://tympanus.net/codrops/2010/05/27/awesome-mobile-image-gallery-web-app/) ([演示](http://tympanus.net/Tutorials/WonderwallMobileGallery/) | [下载](http://tympanus.net/Tutorials/WonderwallMobileGallery/WonderwallMobileGallery.zip)) [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252e10e528.jpg)](http://tympanus.net/codrops/2010/05/27/awesome-mobile-image-gallery-web-app/)
';

几款极好的 JavaScript 文件上传插件

最后更新于:2022-04-01 10:05:27

**[jQuery File Uploader](http://blueimp.github.io/jQuery-File-Upload/basic.html)** [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da42895.jpg)](http://blueimp.github.io/jQuery-File-Upload/basic.html) 这是最受欢迎的 [**jQuery**](http://www.cnblogs.com/lhb25/category/277997.html) 文件上传组件,支持批量上传,拖放上传,显示上传进度条以及校验功能。 支持预览图片、音频和视频,支持跨域上传和客户端图片缩放,支持的服务端平台有:PHP, Python, Ruby on Rails, Java, Node.js, Go 等等。 使用示例: ~~~ $(function() { 'use strict'; // Change this to the location of your server-side upload handler: varurl = window.location.hostname === 'blueimp.github.io'? '//jquery-file-upload.appspot.com/': 'server/php/'; $('#fileupload').fileupload({ url: url, dataType:'json', done:function (e, data) { $.each(data.result.files,function (index, file) { $('<p/>').text(file.name).appendTo('#files'); }); }, progressall:function (e, data) { varprogress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress +'%' ); } }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined :'disabled'); }); ~~~ [插件下载](https://github.com/blueimp/jQuery-File-Upload/archive/8.8.5.zip)[在线演示](http://blueimp.github.io/jQuery-File-Upload/) **[DropZoneJS](http://www.dropzonejs.com/)** [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da568cd.jpg)](http://www.dropzonejs.com/) DropzoneJS 是一个用于现代浏览器的开源的拖放上传插件,最大的特色是即时图片预览功能。 使用方法非常简单,只需添加 class 即可: [?](#) <table cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="html plain">&lt;</code><code class="html keyword">form</code><code class="html color1">id</code><code class="html plain">=</code><code class="html string">"my-awesome-dropzone"</code><code class="html color1">action</code><code class="html plain">=</code><code class="html string">"/target"</code><code class="html color1">class</code><code class="html plain">=</code><code class="html string">"dropzone"</code><code class="html plain">&gt;&lt;/</code><code class="html keyword">form</code><code class="html plain">&gt;</code></div></div></td></tr></tbody></table> 或者手动实例化: [?](#) <table cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="javascript keyword">new</code><code class="javascript plain">Dropzone(</code><code class="javascript string">"div#my-dropzone"</code><code class="javascript plain">, {</code><code class="javascript comments">/* options */</code> <code class="javascript plain">});</code></div></div></td></tr></tbody></table> 可以添加更多参数: [?](#) <table cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="javascript plain">Dropzone.options.myAwesomeDropzone = { maxFilesize: 1 };</code></div></div></td></tr></tbody></table> 发可以自定义事件: [?](#) <table cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="javascript plain">Dropzone.options.myDropzone({</code></div><div class="line number2 index1 alt1"><code class="javascript spaces"/><code class="javascript plain">init:</code><code class="javascript keyword">function</code><code class="javascript plain">() {</code></div><div class="line number3 index2 alt2"><code class="javascript spaces"/><code class="javascript keyword">this</code><code class="javascript plain">.on(</code><code class="javascript string">"error"</code><code class="javascript plain">,</code><code class="javascript keyword">function</code><code class="javascript plain">(file, message) { alert(message); });</code></div><div class="line number4 index3 alt1"><code class="javascript spaces"/><code class="javascript plain">}</code></div><div class="line number5 index4 alt2"><code class="javascript plain">});</code></div><div class="line number6 index5 alt1"><code class="javascript comments">// or if you need to access a Dropzone somewhere else:</code></div><div class="line number7 index6 alt2"><code class="javascript keyword">var</code><code class="javascript plain">myDropzone = Dropzone.forElement(</code><code class="javascript string">"div#my-dropzone"</code><code class="javascript plain">);</code></div><div class="line number8 index7 alt1"><code class="javascript plain">myDropzone.on(</code><code class="javascript string">"error"</code><code class="javascript plain">,</code><code class="javascript keyword">function</code><code class="javascript plain">(file, message) { alert(message); });&lt;span style=</code><code class="javascript string">"line-height: 1.5;"</code><code class="javascript plain">&gt; &lt;/span&gt;</code></div></div></td></tr></tbody></table> [插件下载](https://github.com/enyo/dropzone/archive/master.zip)[在线演示](http://www.dropzonejs.com/) **[Uploadify](http://www.uploadify.com/)** [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da6af70.jpg)](http://www.uploadify.com/) Uploadify 有两个版本,[**HTML5**](http://www.cnblogs.com/lhb25/category/146076.html) 方法上传版本和传统的 Flash 上传。支持高度自定义,可以完美的继承到你的网站中。 Flash 版本兼容性好,使用示例: [?](#) <table cellpadding="0" cellspacing="0" border="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="javascript plain">$(</code><code class="javascript keyword">function</code><code class="javascript plain">() {</code></div><div class="line number2 index1 alt1"><code class="javascript spaces"/><code class="javascript plain">$(</code><code class="javascript string">"#file_upload_1"</code><code class="javascript plain">).uploadify({</code></div><div class="line number3 index2 alt2"><code class="javascript spaces"/><code class="javascript plain">height : 30,</code></div><div class="line number4 index3 alt1"><code class="javascript spaces"/><code class="javascript plain">swf :</code><code class="javascript string">'/uploadify/uploadify.swf'</code><code class="javascript plain">,</code></div><div class="line number5 index4 alt2"><code class="javascript spaces"/><code class="javascript plain">uploader :</code><code class="javascript string">'/uploadify/uploadify.php'</code><code class="javascript plain">,</code></div><div class="line number6 index5 alt1"><code class="javascript spaces"/><code class="javascript plain">width : 120</code></div><div class="line number7 index6 alt2"><code class="javascript spaces"/><code class="javascript plain">});</code></div><div class="line number8 index7 alt1"><code class="javascript plain">});</code></div></div></td></tr></tbody></table> [插件下载](http://www.uploadify.com/wp-content/uploads/files/uploadify.zip)[在线演示](http://www.uploadify.com/demos/) **[FineUploader](http://fineuploader.com/)** [![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da82dd9.jpg)](http://fineuploader.com/) 这个 [**JavaScript**](http://www.cnblogs.com/lhb25/category/146074.html) 插件可以帮助你在网站中集成体验极好的文件上传功能。可以结合 [**jQuery**](http://www.cnblogs.com/lhb25/category/277997.html) 或者 Bootstrap 使用。 主要特色: - 批量上传 - 显示进度条 - 拖放上传 - 自动或者手动上传,可取消 - 自定义错误提示信息 - 自动或者手动重试 - 内置的校验规则 - 可编辑文件名称 使用示例: (1)手动触发上传 ~~~ <divid="manual-fine-uploader"></div> <divid="triggerUpload"class="btn btn-primary"style="margin-top: 10px;"> <iclass="icon-upload icon-white"></i> Upload now </div> <scriptsrc="http://code.jquery.com/jquery-latest.js"></script> <scriptsrc="jquery.fineuploader-{VERSION}.js"></script> <script> $(document).ready(function() { var manualuploader = $('#manual-fine-uploader').fineUploader({ request: { endpoint: 'server/handleUploads' }, autoUpload: false, text: { uploadButton: '<iclass="icon-plus icon-white"></i> Select Files' } }); $('#triggerUpload').click(function() { manualuploader.fineUploader('uploadStoredFiles'); }); }); </script> ~~~ (2)编辑文件名称 ~~~ <!DOCTYPE html> <html> <head> <metacharset="utf-8"> <title>Fine Uploader - jQuery Wrapper Minimal Demo</title> <linkhref="fineuploader-{VERSION}.css"rel="stylesheet"> </head> <body> <divid="jquery-wrapped-fine-uploader"></div> <divid="triggerUpload"class="btn btn-primary"style="margin-top: 10px;"> <iclass="icon-upload icon-white"></i> Upload now </div> <scriptsrc="http://code.jquery.com/jquery-latest.js"></script> <scriptsrc="jquery.fineuploader-{VERSION}.js"></script> <script> $(document).ready(function () { $('#myFineUploader').fineUploader({ request: { endpoint: 'server/handleUploads' }, editFilename: { enabled: true }, autoUpload: false }); $('#triggerUpload').click(function() { $('#myFineuploader').fineUploader('uploadStoredFiles'); }); </script> </body> </html> ~~~ (3)自定义选项 ~~~ <divid="restricted-fine-uploader"></div> <scriptsrc="http://code.jquery.com/jquery-latest.js"></script> <scriptsrc="jquery.fineuploader-{VERSION}.js"></script> <script> $(document).ready(function() { $('#restricted-fine-uploader').fineUploader({ request: { endpoint: 'server/success.html' }, multiple: false, validation: { allowedExtensions: ['jpeg', 'jpg', 'txt'], sizeLimit: 51200 // 50 kB = 50 * 1024 bytes }, text: { uploadButton: 'Click or Drop' }, showMessage: function(message) { // Using Bootstrap's classes $('#restricted-fine-uploader').append('<divclass="alert alert-error">' + message + '</div>'); } }); }); </script> ~~~ (4)显示图片缩略图 ~~~ <divid="thumbnail-fine-uploader"></div> <scriptsrc="http://code.jquery.com/jquery-latest.js"></script> <scriptsrc="jquery.fineuploader-{VERSION}.js"></script> <script> $(document).ready(function() { $('#thumbnail-fine-uploader').fineUploader({ request: { endpoint: 'server/success.html' }, validation: { allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'] }, text: { uploadButton: 'Click or Drop' } }).on('complete', function(event, id, fileName, responseJSON) { if (responseJSON.success) { $(this).append('<imgsrc="img/success.jpg"alt="' + fileName + '">'); } }); }); </script> ~~~ (5)限制文件上传数 ~~~ <divid="filelimit-fine-uploader"></div> <scriptsrc="http://code.jquery.com/jquery-latest.js"></script> <scriptsrc="jquery.fineuploader-{VERSION}.js"></script> <script> $(document).ready(function() { $('#filelimit-fine-uploader').fineUploader({ request: { endpoint: 'server/success.html' }, validation: { itemLimit: 3 } }); }); </script> ~~~ [插件下载](http://www.cnblogs.com/lhb25/p/form-enhanced-with-javascript-one.html)[在线演示](http://fineuploader.com/) 本文转自:http://www.cnblogs.com/lhb25/p/form-enhanced-with-javascript-five.html
';

Web 通信 之 长连接、长轮询(long polling)

最后更新于:2022-04-01 10:05:24

基于HTTP的长连接,是一种通过长轮询方式实现"服务器推"的技术,它弥补了HTTP简单的请求应答模式的不足,极大地增强了程序的实时性和交互性。 ### 一、什么是长连接、长轮询? 用通俗易懂的话来说,就是客户端不停的向服务器发送请求以获取最新的数据信息。这里的“不停”其实是有停止的,只是我们人眼无法分辨是否停止,它只是一种快速的停下然后又立即开始连接而已。 ### 二、长连接、长轮询的应用场景 长连接、长轮询一般应用与WebIM、ChatRoom和一些需要及时交互的网站应用中。其真实案例有:WebQQ、Hi网页版、Facebook IM等。 如果你对服务器端的反向Ajax感兴趣,可以参考这篇文章 DWR 反向Ajax 服务器端推的方式:[http://www.cnblogs.com/hoojo/category/276235.html](http://www.cnblogs.com/hoojo/category/276235.html "http://www.cnblogs.com/hoojo/category/276235.html") 欢迎大家继续支持和关注我的博客: [http://hoojo.cnblogs.com](http://hoojo.cnblogs.com) [http://blog.csdn.net/IBM_hoojo](http://blog.csdn.net/IBM_hoojo) 也欢迎大家和我交流、探讨IT方面的知识。 email:[hoojo_@126.com ### 三、优缺点 **轮询:**客户端定时向服务器发送Ajax请求,服务器接到请求后马上返回响应信息并关闭连接。 优点:后端程序编写比较容易。 缺点:请求中有大半是无用,浪费带宽和服务器资源。 实例:适于小型应用。 **长轮询:**客户端向服务器发送Ajax请求,服务器接到请求后hold住连接,直到有新消息才返回响应信息并关闭连接,客户端处理完响应信息后再向服务器发送新的请求。 优点:在无消息的情况下不会频繁的请求,耗费资源小。 缺点:服务器hold连接会消耗资源,返回数据顺序无保证,难于管理维护。 实例:WebQQ、Hi网页版、Facebook IM。 **长连接:**在页面里嵌入一个隐蔵iframe,将这个隐蔵iframe的src属性设为对一个长连接的请求或是采用xhr请求,服务器端就能源源不断地往客户端输入数据。 优点:消息即时到达,不发无用请求;管理起来也相对方便。 缺点:服务器维护一个长连接会增加开销。 实例:Gmail聊天 **Flash Socket:**在页面中内嵌入一个使用了Socket类的 Flash 程序JavaScript通过调用此Flash程序提供的Socket接口与服务器端的Socket接口进行通信,JavaScript在收到服务器端传送的信息后控制页面的显示。 优点:实现真正的即时通信,而不是伪即时。 缺点:客户端必须安装Flash插件;非HTTP协议,无法自动穿越防火墙。 实例:网络互动游戏。 ### 四、实现原理 所谓长连接,就是要在客户端与服务器之间创建和保持稳定可靠的连接。其实它是一种很早就存在的技术,但是由于浏览器技术的发展比较缓慢,没有为这种机制的实现提供很好的支持。所以要达到这种效果,需要客户端和服务器的程序共同配合来完成。通常的做法是,在服务器的程序中加入一个死循环,在循环中监测数据的变动。当发现新数据时,立即将其输出给浏览器并断开连接,浏览器在收到数据后,再次发起请求以进入下一个周期,这就是常说的长轮询(long-polling)方式。如下图所示,它通常包含以下几个关键过程: [![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d9cf717.png "image")](http://images.cnitblog.com/blog/151517/201309/26143658-a6a4f0ba2ede462095c9d866985ed101.png) 1.轮询的建立 建立轮询的过程很简单,浏览器发起请求后进入循环等待状态,此时由于服务器还未做出应答,所以HTTP也一直处于连接状态中。 2.数据的推送 在循环过程中,服务器程序对数据变动进行监控,如发现更新,将该信息输出给浏览器,随即断开连接,完成应答过程,实现“服务器推”。 3.轮询的终止 轮询可能在以下3种情况时终止: 3.1. 有新数据推送 当循环过程中服务器向浏览器推送信息后,应该主动结束程序运行从而让连接断开,这样浏览器才能及时收到数据。 3.2. 没有新数据推送 循环不能一直持续下去,应该设定一个最长时限,避免WEB服务器超时(Timeout),若一直没有新信息,服务器应主动向浏览器发送本次轮询无新信息的正常响应,并断开连接,这也被称为“心跳”信息。 3.3. 网络故障或异常 由于网络故障等因素造成的请求超时或出错也可能导致轮询的意外中断,此时浏览器将收到错误信息。 4.轮询的重建 浏览器收到回复并进行相应处理后,应马上重新发起请求,开始一个新的轮询周期。 ### 五、程序设计 1、普通轮询 Ajax方式 客户端代码片段 ~~~ <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="author" content="hoojo & http://hoojo.cnblogs.com"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <%@ include file="/tags/jquery-lib.jsp"%> <script type="text/javascript"> $(function () { window.setInterval(function () { $.get("${pageContext.request.contextPath}/communication/user/ajax.mvc", {"timed": new Date().getTime()}, function (data) { $("#logs").append("[data: " + data + " ]<br/>"); }); }, 3000); }); </script> </head> <body> <div id="logs"></div> </body> </html> ~~~ 客户端实现的就是用一种普通轮询的结果,比较简单。利用setInterval不间断的刷新来获取服务器的资源,这种方式的优点就是简单、及时。缺点是链接多数是无效重复的;响应的结果没有顺序(因为是异步请求,当发送的请求没有返回结果的时候,后面的请求又被发送。而此时如果后面的请求比前面的请求要先返回结果,那么当前面的请求返回结果数据时已经是过时无效的数据了);请求多,难于维护、浪费服务器和网络资源。 服务器端代码 ~~~ @RequestMapping("/ajax") public void ajax(long timed, HttpServletResponse response) throws Exception { PrintWriter writer = response.getWriter(); Random rand = new Random(); // 死循环 查询有无数据变化 while (true) { Thread.sleep(300); // 休眠300毫秒,模拟处理业务等 int i = rand.nextInt(100); // 产生一个0-100之间的随机数 if (i > 20 && i < 56) { // 如果随机数在20-56之间就视为有效数据,模拟数据发生变化 long responseTime = System.currentTimeMillis(); // 返回数据信息,请求时间、返回数据时间、耗时 writer.print("result: " + i + ", response time: " + responseTime + ", request time: " + timed + ", use time: " + (responseTime - timed)); break; // 跳出循环,返回数据 } else { // 模拟没有数据变化,将休眠 hold住连接 Thread.sleep(1300); } } } ~~~ 服务器端实现,这里就模拟下程序监控数据的变化。上面代码属于SpringMVC 中controller中的一个方法,相当于Servlet中的一个doPost/doGet方法。如果没有程序环境适应servlet即可,将方法体中的代码copy到servlet的doGet/doPost中即可。 服务器端在进行长连接的程序设计时,要注意以下几点: 1. 服务器程序对轮询的可控性 由于轮询是用死循环的方式实现的,所以在算法上要保证程序对何时退出循环有完全的控制能力,避免进入死循环而耗尽服务器资源。 2. 合理选择“心跳”频率 从图1可以看出,长连接必须由客户端不停地进行请求来维持,所以在客户端和服务器间保持正常的“心跳”至为关键,参数POLLING_LIFE应小于WEB服务器的超时时间,一般建议在10~20秒左右。 3. 网络因素的影响 在实际应用时,从服务器做出应答,到下一次循环的建立,是有时间延迟的,延迟时间的长短受网络传输等多种因素影响,在这段时间内,长连接处于暂时断开的空档,如果恰好有数据在这段时间内发生变动,服务器是无法立即进行推送的,所以,在算法设计上要注意解决由于延迟可能造成的数据丢失问题。 4. 服务器的性能 在长连接应用中,服务器与每个客户端实例都保持一个持久的连接,这将消耗大量服务器资源,特别是在一些大型应用系统中更是如此,大量并发的长连接有可能导致新的请求被阻塞甚至系统崩溃,所以,在进行程序设计时应特别注意算法的优化和改进,必要时还需要考虑服务器的负载均衡和集群技术。 [![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d9e5934.png "image")](http://images.cnitblog.com/blog/151517/201309/26143700-d366a813417c4d2b907531be9a7c62d1.png) 上图是返回的结果,可以看到先发出请求,不一定会最先返回结果。这样就不能保证顺序,造成脏数据或无用的连接请求。可见对服务器或网络的资源浪费。 2、普通轮询 iframe方式 ~~~ <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <%@ include file="/tags/jquery-lib.jsp"%> <script type="text/javascript"> $(function () { window.setInterval(function () { $("#logs").append("[data: " + $($("#frame").get(0).contentDocument).find("body").text() + " ]<br/>"); $("#frame").attr("src", "${pageContext.request.contextPath}/communication/user/ajax.mvc?timed=" + new Date().getTime()); // 延迟1秒再重新请求 window.setTimeout(function () { window.frames["polling"].location.reload(); }, 1000); }, 5000); }); </script> </head> <body> <iframe id="frame" name="polling" style="display: none;"></iframe> <div id="logs"></div> </body> </html> ~~~ 这里的客户端程序是利用隐藏的iframe向服务器端不停的拉取数据,将iframe获取后的数据填充到页面中即可。同ajax实现的基本原理一样,唯一不同的是当一个请求没有响应返回数据的情况下,下一个请求也将开始,这时候前面的请求将被停止。如果要使程序和上面的ajax请求一样也可以办到,那就是给每个请求分配一个独立的iframe即可。下面是返回的结果: [![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da02232.png "image")](http://images.cnitblog.com/blog/151517/201309/26143702-5b82feb05c9d4ba3a2149b28b8395adf.png) 其中红色是没有成功返回请求就被停止(后面请求开始)掉的请求,黑色是成功返回数据的请求。 3、长连接iframe方式 ~~~ <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="author" content="hoojo & http://hoojo.cnblogs.com"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <%@ include file="/tags/jquery-lib.jsp"%> <script type="text/javascript"> $(function () { window.setInterval(function () { var url = "${pageContext.request.contextPath}/communication/user/ajax.mvc?timed=" + new Date().getTime(); var $iframe = $('<iframe id="frame" name="polling" style="display: none;" src="' + url + '"></iframe>'); $("body").append($iframe); $iframe.load(function () { $("#logs").append("[data: " + $($iframe.get(0).contentDocument).find("body").text() + " ]<br/>"); $iframe.remove(); }); }, 5000); }); </script> </head> <body> <div id="logs"></div> </body> </html> ~~~ 这个轮询方式就是把刚才上面的稍微改下,每个请求都有自己独立的一个iframe,当这个iframe得到响应的数据后就把数据push到当前页面上。使用此方法已经类似于ajax的异步交互了,这种方法也是不能保证顺序的、比较耗费资源、而且总是有一个加载的条在地址栏或状态栏附件(当然要解决可以利用htmlfile,Google的攻城师们已经做到了,网上也有封装好的lib库),但客户端实现起来比较简单。 如果要保证有序,可以不使用setInterval,将创建iframe的方法放在load事件中即可,即使用**递归方式**。调整后的代码片段如下: ~~~ <script type="text/javascript"> $(function () { (function iframePolling() { var url = "${pageContext.request.contextPath}/communication/user/ajax.mvc?timed=" + new Date().getTime(); var $iframe = $('<iframe id="frame" name="polling" style="display: none;" src="' + url + '"></iframe>'); $("body").append($iframe); $iframe.load(function () { $("#logs").append("[data: " + $($iframe.get(0).contentDocument).find("body").text() + " ]<br/>"); $iframe.remove(); // 递归 iframePolling(); }); })(); }); </script> ~~~ 这种方式虽然保证了请求的顺序,但是它不会处理请求延时的错误或是说很长时间没有返回结果的请求,它会一直等到返回请求后才能创建下一个iframe请求,总会和服务器保持一个连接。和以上轮询比较,缺点就是消息不及时,但保证了请求的顺序。 4、ajax实现长连接 ~~~ <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <%@ include file="/tags/jquery-lib.jsp"%> <script type="text/javascript"> $(function () { (function longPolling() { $.ajax({ url: "${pageContext.request.contextPath}/communication/user/ajax.mvc", data: {"timed": new Date().getTime()}, dataType: "text", timeout: 5000, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]<br/>"); if (textStatus == "timeout") { // 请求超时 longPolling(); // 递归调用 // 其他错误,如网络错误等 } else { longPolling(); } }, success: function (data, textStatus) { $("#state").append("[state: " + textStatus + ", data: { " + data + "} ]<br/>"); if (textStatus == "success") { // 请求成功 longPolling(); } } }); })(); }); </script> </head> <body> ~~~ 上面这段代码就是才有Ajax的方式完成长连接,主要优点就是和服务器始终保持一个连接。如果当前连接请求成功后,将更新数据并且继续创建一个新的连接和服务器保持联系。如果连接超时或发生异常,这个时候程序也会创建一个新连接继续请求。这样就大大节省了服务器和网络资源,提高了程序的性能,从而也保证了程序的顺序。 [![image](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252da1b8cc.png "image")](http://images.cnitblog.com/blog/151517/201309/26143705-93d90ebd030442bba75f07089be3eeb9.png) ### 六、总结 现代的浏览器都支持跨域资源共享(Cross-Origin Resource Share,CORS)规范,该规范允许XHR执行跨域请求,因此基于脚本的和基于iframe的技术已成为了一种过时的需要。 把Comet做为反向Ajax的实现和使用的最好方式是通过XMLHttpRequest对象,该做法提供了一个真正的连接句柄和错误处理。当然你选择经由HTTP长轮询使用XMLHttpRequest对象(在服务器端挂起的一个简单的Ajax请求)的Comet模式,所有支持Ajax的浏览器也都支持该种做法。 基于HTTP的长连接技术,是目前在纯浏览器环境下进行即时交互类应用开发的理想选择,随着浏览器的快速发展,html5将为其提供更好的支持和更广泛的应用。在html5中有一个websocket 可以很友好的完成长连接这一技术,网上也有相关方面的资料,这里也就不再做过多介绍。
';

JavaScript/jQuery、HTML、CSS 构建 Web IM 远程及时聊天通信程序

最后更新于:2022-04-01 10:05:22

这篇文章主要介绍用JavaScript和jQuery、HTML、CSS以及用第三方聊天JavaScript(jsjac)框架构建一个BS Web的聊天应用程序。此程序可以和所有连接到Openfire服务器的应用进行通信、发送消息。如果要运行本程序还需要一个聊天服务器Openfire, 以及需要用到Http方式和Openfire通信的第三方库(JabberHTTPBind)。 JabberHTTPBind是jabber提供的XMPP协议通信的Http bind发送的形式,它可以完成WebBrowser和Openfire建立长连接通信。 主要通信流程如下图所示: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d76b623.jpg) 用户A通过JavaScript jsjac.js库发送一条消息到JabberHTTPBind这个Servlet容器,然后JabberHTTPBind的Servlet容器会向Openfire发送XMPP协议的XML报文。Openfire Server接收到报文后解析,然后发送给指定的用户B。JabberHTTPBind获取到Openfire Server发送的数据后,解析报文向当前Servlet容器中的链接的Session中找到指定的用户再发送数据给用户B。 WebBrowser端用的是jsjac和JabberHTTPBind建立的连接,所有数据都要经过JabberHTTPBind解析/转换发送给Openfire。 先上张图看看效果,呵呵~这里是用户hoojo和girl的聊天画面,双方在进行互聊…… ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d78767c.png) 可以发送表情、改变字体样式(对方界面也可以看到你的字体样式),同时右侧是显示/收缩详情的信息 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d79a62a.png) 收缩详情 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d7dcc58.png) 聊天界面部分截图 用户登录、注册,sendTo表示你登录后向谁发送聊天消息、并且建立一个聊天窗口 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d7f0d4a.png) ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d80bb7c.png) 登录成功后,你可以在日志控制台看到你的登陆状态、或是在firebug控制台中看到你的连接请求状态 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d82117e.png) ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d834b00.png) 登陆失败 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d84627e.png) 只有connecting,就没有下文了 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d857259.png) 登陆成功后,你就可以给指定用户发送消息,且设置你想发送消息的新用户点击new Chat按钮创建新会话 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d96baba.png) 如果你来了新消息,在浏览器的标题栏会有新消息提示 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d985d56.png) 如果你当前聊天界面的窗口都是关闭状态,那么在右下角会有消息提示的闪动图标 这里已经贴出了所有的源代码了,如果你非常的需要源代码(但我希望你能自己创建一个工程去复制源代码,这是我希望看到的),那么你可以通过以下方式联系我 Email:hoojo_@126.com Blog:[http://blog.csdn.net/IBM_hoojo](http://blog.csdn.net/IBM_hoojo) [http://hoojo.cnblogs.com/](http://hoojo.cnblogs.com/) [http://hoojo.blogjava.net](http://hoojo.blogjava.net) **注:我不会保证在第一时间给你代码,但我会在空闲的时间给你发送源码** **导读** 如果你对openfire还不是很了解或是不知道安装,建议你看看这2篇文章 [http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html](http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html "http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.html") [http://www.cnblogs.com/hoojo/archive/2012/05/13/2498151.html](http://www.cnblogs.com/hoojo/archive/2012/05/13/2498151.html "http://www.cnblogs.com/hoojo/archive/2012/05/13/2498151.html") 因为这里还用到了JabberHTTPBind 以及在使用它或是运行示例的时候会遇到些问题,那么你可以看看这篇文章 [http://www.cnblogs.com/hoojo/archive/2012/05/17/2506845.html](http://www.cnblogs.com/hoojo/archive/2012/05/17/2506845.html "http://www.cnblogs.com/hoojo/archive/2012/05/17/2506845.html") 开发环境 System:Windows JavaEE Server:Tomcat 5.0.28+/Tomcat 6 WebBrowser:IE6+、Firefox3.5+、Chrome 已经兼容浏览器 JavaSDK:JDK 1.6+ Openfire 3.7.1 IDE:eclipse 3.2、MyEclipse 6.5 开发依赖库 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d994084.png) jdk1.4+ serializer.jar xalan.jar jhb-1.0.jar log4j-1.2.16.jar jhb-1.0.jar 这个就是JabberHTTPBind,我把编译的class打成jar包了 JavaScript lib ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d9a4c16.png) **jquery.easydrag.js** 窗口拖拽JavaScript lib **jquery-1.7.1.min.js** jquery lib **jsjac.js** 通信核心库 **local.chat-2.0.js** 本地会话窗口发送消息JavaScript库 **remote.jsjac.chat-2.0.js** 远程会话消息JavaScript库 **send.message.editor-1.0.js** 窗口编辑器JavaScript库 ### 一、准备工作 [jsjac](http://blog.jwchat.org/jsjac/) JavaScript lib下载:[https://github.com/sstrigler/JSJaC/](https://github.com/sstrigler/JSJaC/ "https://github.com/sstrigler/JSJaC/") 如果你不喜欢用jsjac JavaScript lib和Openfire通信,那么有一款jQuery的plugin可以供你使用,下载地址 jQuery-XMPP-plugin [https://github.com/maxpowel/jQuery-XMPP-plugin](https://github.com/maxpowel/jQuery-XMPP-plugin "https://github.com/maxpowel/jQuery-XMPP-plugin") 这里有所以能支持Openfire通信的第三方库,有兴趣的可以研究下 [http://xmpp.org/xmpp-software/libraries/](http://xmpp.org/xmpp-software/libraries/ "http://xmpp.org/xmpp-software/libraries/") jquery.easydrag 下载:[http://fromvega.com/code/easydrag/jquery.easydrag.js](http://fromvega.com/code/easydrag/jquery.easydrag.js "http://fromvega.com/code/easydrag/jquery.easydrag.js") jquery 下载:[http://code.jquery.com/jquery-1.7.1.min.js](http://code.jquery.com/jquery-1.7.1.min.js "http://code.jquery.com/jquery-1.7.2.min.js") JabberHTTPBind jhb.jar 下载:[http://download.csdn.net/detail/ibm_hoojo/4489188](http://download.csdn.net/detail/ibm_hoojo/4489188 "http://download.csdn.net/detail/ibm_hoojo/4489188") images 图片素材:[http://download.csdn.net/detail/ibm_hoojo/4489439](http://download.csdn.net/detail/ibm_hoojo/4489439 "http://download.csdn.net/detail/ibm_hoojo/4489439") 工程目录结构 ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d9b85d2.png) ### 二、核心代码演示 **1、主界面(登陆、消息提示、日志、建立新聊天窗口)代码 index.jsp** ~~~ <%@ page language="java" pageEncoding="UTF-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>WebIM Chat</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="author" content="hoojo"> <meta http-equiv="email" content="hoojo_@126.com"> <meta http-equiv="blog" content="http://blog.csdn.net/IBM_hoojo"> <meta http-equiv="blog" content="http://hoojo.cnblogs.com"> <link rel="stylesheet" type="text/css" href="css/chat-2.0.css" /> <script type="text/javascript"> window.contextPath = "<%=path%>"; window["serverDomin"] = "192.168.8.22"; </script> <script type="text/javascript" src="jslib/jquery-1.7.1.min.js"></script> <script type="text/javascript" src="jslib/jsjac.js"></script> <!-- script type="text/javascript" src="debugger/Debugger.js"></script--> <script type="text/javascript" src="jslib/send.message.editor-1.0.js"></script> <script type="text/javascript" src="jslib/jquery.easydrag.js"></script> <script type="text/javascript" src="jslib/remote.jsjac.chat-2.0.js"></script> <script type="text/javascript" src="jslib/local.chat-2.0.js"></script> <script type="text/javascript"> $(function () { $("#login").click(function () { var userName = $(":text[name='userName']").val(); var receiver = $("*[name='to']").val(); // 建立一个聊天窗口应用,并设置发送者和消息接收者 $.WebIM({ sender: userName, receiver: receiver }); // 登陆到openfire服务器 remote.jsjac.chat.login(document.userForm); $("label").text(userName); $("form").hide(); $("#newConn").show(); }); $("#logout").click(function () { // 退出openfire登陆,断开链接 remote.jsjac.chat.logout(); $("form").show(); $("#newConn").hide(); $("#chat").hide(800); }); $("#newSession").click(function () { var receiver = $("#sendTo").val(); // 建立一个新聊天窗口,并设置消息接收者(发送给谁?) $.WebIM.newWebIM({ receiver: receiver }); }); }); </script> </head> <body> <!-- 登陆表单 --> <form name="userForm" style="background-color: #fcfcfc; width: 100%;"> userName:<input type="text" name="userName" value="boy"/> password:<input type="password" name="password" value="boy"/> register: <input type="checkbox" name="register"/> sendTo: <input type="text" id="to" name="to" value="hoojo" width="10"/> <input type="button" value="Login" id="login"/> </form> <!-- 新窗口聊天 --> <div id="newConn" style="display: none; background-color: #fcfcfc; width: 100%;"> User:<label></label> sendTo: <input type="text" id="sendTo" value="hoojo" width="10"/> <input type="button" value="new Chat" id="newSession"/> <input type="button" value="Logout" id="logout"/> </div> <!-- 日志信息 --> <div id="error" style="display: ; background-color: red;"></div> <div id="info" style="display: ; background-color: #999999;"></div> <!-- 聊天来消息提示 --> <div class="chat-message"> <img src="images/write_icon.png" class="no-msg"/> <img src="images/write_icon.gif" class="have-msg" style="display: none;"/> </div> </body> </html> ~~~ 下面这段代码尤为重要,它是设置你链接openfire的地址。这个地址一段错误你将无法进行通信! ~~~ <script type="text/javascript"> window.contextPath = "<%=path%>"; window["serverDomin"] = "192.168.8.22"; </script> ~~~ $.WebIM方法是主函数,用它可以覆盖local.chat中的基本配置,它可以完成聊天窗口的创建。$.WebIM.newWebIM方法是新创建一个窗口,只是消息的接收者是一个新用户。 ~~~ $.WebIM({ sender: userName, receiver: receiver }); $.WebIM.newWebIM({ receiver: receiver }); ~~~ remote.jsjac.chat.login(document.userForm);方法是用户登录到Openfire服务器 参数如下: ~~~ httpbase: window.contextPath + "/JHB/", //请求后台http-bind服务器url domain: window["serverDomin"], //"192.168.5.231", // 192.168.5.231 当前有效域名 username: "", // 登录用户名 pass: "", // 密码 timerval: 2000, // 设置请求超时 resource: "WebIM", // 链接资源标识 register: true // 是否注册 ~~~ remote.jsjac.chat.logout();是退出、断开openfire的链接 **2、本地聊天应用核心代码 local.chat-2.0.js** ~~~ /*** * jquery local chat * @version v2.0 * @createDate -- 2012-5-28 * @author hoojo * @email hoojo_@126.com * @blog http://hoojo.cnblogs.com & http://blog.csdn.net/IBM_hoojo * @requires jQuery v1.2.3 or later, send.message.editor-1.0.js * Copyright (c) 2012 M. hoo **/ ;(function ($) { if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) { alert('WebIM requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery); return; } var faceTimed, count = 0; var _opts = defaultOptions = { version: 2.0, chat: "#chat", chatEl: function () { var $chat = _opts.chat; if ((typeof _opts.chat) == "string") { $chat = $(_opts.chat); } else if ((typeof _opts.chat) == "object") { if (!$chat.get(0)) { $chat = $($chat); } } return $chat; }, sendMessageIFrame: function (receiverId) { return $("iframe[name='sendMessage" + receiverId + "']").get(0).contentWindow; }, receiveMessageDoc: function (receiverId) { receiverId = receiverId || ""; var docs = []; $.each($("iframe[name^='receiveMessage" + receiverId + "']"), function () { docs.push($(this.contentWindow.document)); }); return docs; //return $($("iframe[name^='receiveMessage" + receiverId + "']").get(0).contentWindow.document); }, sender: "", // 发送者 receiver: "", // 接收者 setTitle: function (chatEl) { var receiver = this.getReceiver(chatEl); chatEl.find(".title").html("和" + receiver + "聊天对话中"); }, getReceiver: function (chatEl) { var receiver = chatEl.attr("receiver"); if (~receiver.indexOf("@")) { receiver = receiver.split("@")[0]; } return receiver; }, // 接收消息iframe样式 receiveStyle: [ '<html>', '<head><style type="text/css">', 'body{border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace;}', '.msg{margin-left: 1em;}p{margin:0;padding:0;}.me{color: blue;}.you{color:green;}', '</style></head>', '<body></body>', '</html>' ].join(""), writeReceiveStyle: function (receiverId) { this.receiveMessageDoc(receiverId)[0].get(0).write(this.receiveStyle); }, datetimeFormat: function (v) { if (~~v < 10) { return "0" + v; } return v; }, getDatetime: function () { // 设置当前发送日前 var date = new Date(); var datetime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate(); datetime = " " + _opts.datetimeFormat(date.getHours()) + ":" + _opts.datetimeFormat(date.getMinutes()) + ":" + _opts.datetimeFormat(date.getSeconds()); return datetime; }, /*** * 发送消息的格式模板 * flag = true 表示当前user是自己,否则就是对方 **/ receiveMessageTpl: function (userName, styleTpl, content, flag) { var userCls = flag ? "me" : "you"; if (styleTpl && flag) { content = [ "<span style='", styleTpl, "'>", content, "</span>" ].join(""); } return [ '<p class="', userCls, '">', _opts.getDatetime(), ' ', userName, ':</p>', '<p class="msg">', content, '</p>' ].join(""); }, // 工具类按钮触发事件返回html模板 sendMessageStyle: { cssStyle: { bold: "font-weight: bold;", underline: "text-decoration: underline;", italic: "font-style: oblique;" }, setStyle: function (style, val) { if (val) { _opts.sendMessageStyle[style] = val; } else { var styleVal = _opts.sendMessageStyle[style]; if (styleVal === undefined || !styleVal) { _opts.sendMessageStyle[style] = true; } else { _opts.sendMessageStyle[style] = false; } } }, getStyleTpl: function () { var tpl = ""; $.each(_opts.sendMessageStyle, function (style, item) { //alert(style + "#" + item + "#" + (typeof item)); if (item === true) { tpl += _opts.sendMessageStyle.cssStyle[style]; } else if ((typeof item) === "string") { //alert(style + "-------------" + sendMessageStyle[style]); tpl += style + ":" + item + ";"; } }); return tpl; } }, // 向接收消息iframe区域写消息 writeReceiveMessage: function (receiverId, userName, content, flag) { if (content) { // 发送消息的样式 var styleTpl = _opts.sendMessageStyle.getStyleTpl(); var receiveMessageDoc = _opts.receiveMessageDoc(receiverId); $.each(receiveMessageDoc, function () { var $body = this.find("body"); // 向接收信息区域写入发送的数据 $body.append(_opts.receiveMessageTpl(userName, styleTpl, content, flag)); // 滚动条滚到底部 this.scrollTop(this.height()); }); } }, // 发送消息 sendHandler: function ($chatMain) { var doc = $chatMain.find("iframe[name^='sendMessage']").get(0).contentWindow.document; var content = doc.body.innerHTML; content = $.trim(content); content = content.replace(new RegExp("<br>", "gm"), ""); // 获取即将发送的内容 if (content) { var sender = $chatMain.attr("sender"); var receiverId = $chatMain.attr("id"); // 接收区域写消息 _opts.writeReceiveMessage(receiverId, sender, content, true); //############# XXX var receiver = $chatMain.find("#to").val(); //var receiver = $chatMain.attr("receiver"); // 判断是否是手机端会话,如果是就发送纯text,否则就发送html代码 var flag = _opts.isMobileClient(receiver); if (flag) { var text = $(doc.body).text(); text = $.trim(text); if (text) { // 远程发送消息 remote.jsjac.chat.sendMessage(text, receiver); } } else { // 非手机端通信 可以发送html代码 var styleTpl = _opts.sendMessageStyle.getStyleTpl(); content = [ "<span style='", styleTpl, "'>", content, "</span>" ].join(""); remote.jsjac.chat.sendMessage(content, receiver); } // 清空发送区域 $(doc).find("body").html(""); } }, faceImagePath: "images/emotions/", faceElTpl: function (i) { return [ "<img src='", this.faceImagePath, (i - 1), "fixed.bmp' gif='", this.faceImagePath, (i - 1), ".gif'/>" ].join(""); }, // 创建表情html elements createFaceElement: function ($chat) { var faces = []; for (var i = 1; i < 100; i++) { faces.push(this.faceElTpl(i)); if (i % 11 == 0) { faces.push("<br/>"); } } $chat.find("#face").html(faces.join("")); this.faceHandler($chat); }, // 插入表情 faceHandler: function ($chat) { $chat.find("#face img").click(function () { $chat.find("#face").hide(150); var imgEL = "<img src='" + $(this).attr("gif") + "'/>"; var $chatMain = $(this).parents(".chat-main"); var win = $chatMain.find("iframe[name^='sendMessage']").get(0).contentWindow; var doc = win.document; sendMessageEditor.insertAtCursor(imgEL, doc, win); }); // 表情隐藏 $chat.find("#face, #face img").mouseover(function () { window.clearTimeout(faceTimed); }).mouseout(function () { window.clearTimeout(faceTimed); faceTimed = window.setTimeout(function () { $chat.find("#face").hide(150); }, 700); }); }, /*** * 发送消息工具栏按钮事件方法 **/ toolBarHandler: function () { var $chat = $(this).parents(".chat-main"); var targetCls = $(this).attr("class"); if (targetCls == "face") { $chat.find("#face").show(150); window.clearTimeout(faceTimed); faceTimed = window.setTimeout(function () { $chat.find("#face").hide(150); }, 1000); } else if (this.tagName == "DIV") { _opts.sendMessageStyle.setStyle(targetCls); } else if (this.tagName == "SELECT") { _opts.sendMessageStyle.setStyle($(this).attr("name"), $(this).val()); if ($(this).attr("name") == "color") { $(this).css("background-color", $(this).val()); } } // 设置sendMessage iframe的style css _opts.writeSendStyle(); }, // 设置sendMessage iframe的style css writeSendStyle: function () { var styleTpl = _opts.sendMessageStyle.getStyleTpl(); var styleEL = ['<style type="text/css">body{', styleTpl,'}</style>'].join(""); $("body").find("iframe[name^='sendMessage']").each(function () { var $head = $(this.contentWindow.document).find("head"); if ($head.find("style").size() > 1) { $head.find("style:gt(0)").remove(); } if (styleTpl) { $head.append(styleEL); } }); }, isMobileClient: function (receiver) { var moblieClients = ["iphone", "ipad", "ipod", "wp7", "android", "blackberry", "Spark", "warning", "symbian"]; var flag = false; for (var i in moblieClients) { if (~receiver.indexOf(moblieClients[i])) { return true; } } return false; }, // 聊天界面html元素 chatLayoutTemplate: function (userJID, sender, receiver, product, flag) { var display = ""; if (flag) { display = "style='display: none;'"; } return [ '<div class="chat-main" id="', userJID, '" sender="', sender, '" receiver="', receiver, '">', '<div id="chat"><div class="radius">', '<table>', '<tr>', '<td colspan="3" class="title"></td>', '</tr>', '<tr>', '<td class="receive-message">', '<iframe name="receiveMessage', userJID,'" frameborder="0" width="100%" height="100%"></iframe>', '</td>', '<td rowspan="4" class="split" ', display, '> </td>', '<td rowspan="4" class="product-info" ', display, '>', '<ul>', '<div class="header"> 商品详情</div>', '<li class="pic">', '<img src="', product.pic, '"/></li>', '<li class="product-name">', product.name, '</li>', '<li class="price">团购价:<span>', product.price, '</span>元</li>', '<li class="market-price">市场价:<s><i>', product.marketPrice, '</i></s>元</li>', '<li>快递公司:', product.deliverOrgs, '</li>', '<li>仓库:', product.wareHouses, '</li>', product.skuAttrs, '</ul>', '</td>', '</tr>', '<tr class="tool-bar">', '<td>', '<select name="font-family" class="family">', '<option>宋体</option>', '<option>黑体</option>', '<option>幼圆</option>', '<option>华文行楷</option>', '<option>华文楷体</option>', '<option>华文楷体</option>', '<option>华文彩云</option>', '<option>华文隶书</option>', '<option>微软雅黑</option>', '<option>Fixedsys</option>', '</select>', '<select name="font-size">', '<option value="12px">大小</option>', '<option value="10px">10</option>', '<option value="12px">12</option>', '<option value="14px">14</option>', '<option value="16px">16</option>', '<option value="18px">18</option>', '<option value="20px">20</option>', '<option value="24px">24</option>', '<option value="28px">28</option>', '<option value="36px">36</option>', '<option value="42px">42</option>', '<option value="52px">52</option>', '</select>', '<select name="color">', '<option value="" selected="selected">颜色</option>', '<option value="#000000" style="background-color:#000000"></option>', '<option value="#FFFFFF" style="background-color:#FFFFFF"></option>', '<option value="#008000" style="background-color:#008000"></option>', '<option value="#800000" style="background-color:#800000"></option>', '<option value="#808000" style="background-color:#808000"></option>', '<option value="#000080" style="background-color:#000080"></option>', '<option value="#800080" style="background-color:#800080"></option>', '<option value="#808080" style="background-color:#808080"></option>', '<option value="#FFFF00" style="background-color:#FFFF00"></option>', '<option value="#00FF00" style="background-color:#00FF00"></option>', '<option value="#00FFFF" style="background-color:#00FFFF"></option>', '<option value="#FF00FF" style="background-color:#FF00FF"></option>', '<option value="#FF0000" style="background-color:#FF0000"></option>', '<option value="#0000FF" style="background-color:#0000FF"></option>', '<option value="#008080" style="background-color:#008080"></option>', '</select>', '<div class="bold"></div>', '<div class="underline"></div>', '<div class="italic"></div>', '<div class="face"></div>', '<div class="history">消息记录</div>', '</td>', '</tr>', '<tr class="send-message">', '<td>', '<iframe name="sendMessage', userJID,'" width="100%" height="80px" frameborder="0"></iframe>', '</td>', '</tr>', '<tr class="bottom-bar">', '<td><input type="text" id="to" name="to" value="hoojo" style="width: 100px;"/><input type="button" value="关闭" id="close"/> ', '<input type="button" value="发送(Enter)" id="send"/> </td>', '</tr>', '</table></div>', '<div id="face"></div>', '</div>', '</div>' ].join(""); }, initWebIM: function (userJID, receiver) { var product = { name: "小玩熊", pic: "http://avatar.csdn.net/9/7/A/2_ibm_hoojo.jpg", price: "198.00", marketPrice: "899.90", deliverOrgs: "EMS", wareHouses: "A库", skuAttrs: "" }; var chatEl = $(_opts.chatLayoutTemplate(userJID, _opts.sender, receiver, product)); $("body").append(chatEl); // 拖拽 $("#" + userJID).easydrag(); // 初始化sendMessageEditor相关信息 sendMessageEditor.iframe = this.sendMessageIFrame(userJID); sendMessageEditor.init(userJID); _opts.setTitle(chatEl); _opts.writeReceiveStyle(userJID); _opts.writeSendStyle(); _opts.createFaceElement(chatEl); // 查看更多详情 chatEl.find(".more").click(function () { var $ul = $(this).parents("ul"); $ul.find(".more").toggle(); $ul.find(".info").toggle(); $ul.find(".pic").toggle(); }); // 收缩详情 chatEl.find(".split").toggle(function () { $(".product-info").hide(); $(this).parents(".radius").css("border-right-width", "0"); }, function () { $(".product-info").show(); $(this).parents(".radius").css("border-right-width", "8px"); }); // 工具类绑定事件 settings.toolBarHandler chatEl.find(".tool-bar td").children().click(this.toolBarHandler); chatEl.find("#send").click(function () { var $chatMain = $(this).parents(".chat-main"); _opts.sendHandler($chatMain); }); chatEl.find("#close").click(function () { var $chatMain = $(this).parents(".chat-main"); $chatMain.hide(500); }); // 首先取消事件绑定,当一次性发多条消息的情况下会同时绑定多个相同事件 $(".have-msg, .no-msg, .chat-main").unbind("click"); $(".have-msg").bind("click", function () { $(this).hide(); $(".no-msg").show(); $(".chat-main:hidden").show(150); }); $(".no-msg").click(function () { $(".chat-main:hidden").each(function (i, item) { var top = i * 10 + 50; var left = i * 20 + 50; $(this).show(500).css({top: top, left: left}); }); }); $(".chat-main").click(function () { $(".chat-main").css("z-index", 9999); $(this).css({"z-index": 10000}); }); $(this.sendMessageIFrame(userJID).document).keyup(function (event) { var e = event || window.event; var keyCode = e.which || e.keyCode; if (keyCode == 13) { var $chatMain = $("#" + $(this).find("body").attr("jid")); _opts.sendHandler($chatMain); } }); }, // 建立新聊天窗口 newWebIM: function (settings) { var chatUser = remote.userAddress(settings.receiver); var userJID = "u" + hex_md5(chatUser); _opts.initWebIM(userJID, chatUser); $("#" + userJID).find(remote.receiver).val(chatUser); $("#" + userJID).show(220); }, // 远程发送消息时执行函数 messageHandler: function (user, content) { var userName = user.split("@")[0]; var tempUser = user; if (~tempUser.indexOf("/")) { tempUser = tempUser.substr(0, tempUser.indexOf("/")); } var userJID = "u" + hex_md5(tempUser); // 首次初始webIM if (!$("#" + userJID).get(0)) { // 初始IM面板; _opts.initWebIM(userJID, user); } // 设置消息接受者的名称 $("#" + userJID).find(remote.receiver).val(user); if ($("#" + userJID).get(0)) { // 消息提示 if ($("div[id='" + userJID + "']:hidden").get(0)) { var haveMessage = $(".have-msg"); haveMessage.show(); $(".no-msg").hide(); } _opts.messageTip("闪聊有了新消息,请查收!"); // 向chat接收信息区域写消息 remote.jsjac.chat.writeMessage(userJID, userName, content); } }, // 消息提示 messageTip: function () { if (count % 2 == 0) { window.focus(); document.title = "你来了新消息,请查收!"; } else { document.title = ""; } if (count > 4) { document.title = ""; count = 0; } else { window.setTimeout(_opts.messageTip, 1000); count ++; } } }; // 初始化远程聊天程序相关方法 var initRemoteIM = function (settings) { // 初始化远程消息 remote.jsjac.chat.init(); // 设置客户端写入信息方法 remote.jsjac.chat.writeReceiveMessage = settings.writeReceiveMessage; // 注册事件 $(window).bind({ unload: remote.jsjac.chat.unloadHandler, error: remote.jsjac.chat.errorHandler, beforeunload: remote.jsjac.chat.logout }); } $.extend({ WebIM: function (opts) { opts = opts || {}; // 覆盖默认配置 defaultOptions = $.extend(defaultOptions, defaultOptions, opts); var settings = $.extend({}, defaultOptions, opts); initRemoteIM(settings); settings.newWebIM(settings); $.WebIM.settings = settings; } }); $.WebIM.settings = $.WebIM.settings || _opts; $.WebIM.initWebIM = _opts.initWebIM; $.WebIM.newWebIM = _opts.newWebIM; $.WebIM.messageHandler = _opts.messageHandler; })(jQuery); ~~~ 这里的方法基本上是聊天窗口上的应用,主要是本地聊天程序的js、HTML元素的操作。如字体、字体大小、颜色、表情、消息的发送等,不涉及到聊天消息发送的核心代码,其中有用到发送远程消息的方法。 remote.jsjac.chat.sendMessage(text, receiver); 这个是发送远程消息的方法,参数1是消息内容、参数2是消息的接收者 如果你有看到这篇文章[http://www.cnblogs.com/hoojo/archive/2012/06/18/2553886.html](http://www.cnblogs.com/hoojo/archive/2012/06/18/2553886.html "http://www.cnblogs.com/hoojo/archive/2012/06/18/2553886.html") 它是一个单纯的WebIM本地的聊天界面。 **3、远程聊天JavaScript核心代码,它是和jsjac库关联的。** remote.jsjac.chat-2.0.js ~~~ /** * IM chat jsjac remote message * @author: hoojo * @email: hoojo_@126.com * @blog http://hoojo.cnblogs.com & http://blog.csdn.net/IBM_hoojo * @createDate: 2012-5-24 * @version 2.0 * @requires jQuery v1.2.3 or later * Copyright (c) 2012 M. hoo **/ var remote = { debug: "info, error", chat: "body", receiver: "#to", // 接受者jquery expression console: { errorEL: function () { if ($(remote.chat).get(0)) { return $(remote.chat).find("#error"); } else { return $("body").find("#error"); } }, infoEL: function () { if ($(remote.chat).get(0)) { return $(remote.chat).find("#info"); } else { return $("body").find("#info"); } }, // debug info info: function (html) { if (~remote.debug.indexOf("info")) { remote.console.infoEL().append(html); remote.console.infoEL().get(0).lastChild.scrollIntoView(); } }, // debug error error: function (html) { if (~remote.debug.indexOf("error")) { remote.console.errorEL().append(html); } }, // clear info/debug console clear: function (s) { if ("debug" == s) { remote.console.errorEL().html(""); } else { remote.console.infoEL().html(""); } } }, userAddress: function (user) { if (user) { if (!~user.indexOf("@")) { user += "@" + remote.jsjac.domain;// + "/" + remote.jsjac.resource; } else if (~user.indexOf("/")) { user = user.substr(0, user.indexOf("/")); } } return user; }, jsjac: { httpbase: window.contextPath + "/JHB/", //请求后台http-bind服务器url domain: window["serverDomin"], //"192.168.5.231", // 192.168.5.231 当前有效域名 username: "", pass: "", timerval: 2000, // 设置请求超时 resource: "WebIM", // 链接资源标识 register: true // 是否注册 } }; remote.jsjac.chat = { writeReceiveMessage: function () { }, setState: function () { var onlineStatus = new Object(); onlineStatus["available"] = "在线"; onlineStatus["chat"] = "欢迎聊天"; onlineStatus["away"] = "离开"; onlineStatus["xa"] = "不可用"; onlineStatus["dnd"] = "请勿打扰"; onlineStatus["invisible"] = "隐身"; onlineStatus["unavailable"] = "离线"; remote.jsjac.chat.state = onlineStatus; return onlineStatus; }, state: null, init: function () { // Debugger plugin if (typeof (Debugger) == "function") { remote.dbger = new Debugger(2, remote.jsjac.resource); remote.dbger.start(); } else { // if you're using firebug or safari, use this for debugging // oDbg = new JSJaCConsoleLogger(2); // comment in above and remove comments below if you don't need debugging remote.dbger = function () { }; remote.dbger.log = function () { }; } try { // try to resume a session if (JSJaCCookie.read("btype").getValue() == "binding") { remote.connection = new JSJaCHttpBindingConnection({ "oDbg": remote.dbger}); rdbgerjac.chat.setupEvent(remote.connection); if (remote.connection.resume()) { remote.console.clear("debug"); } } } catch (e) { remote.console.errorEL().html(e.name + ":" + e.message); } // reading cookie failed - never mind remote.jsjac.chat.setState(); }, login: function (loginForm) { remote.console.clear("debug"); // reset try { // 链接参数 var connectionConfig = remote.jsjac; // Debugger console if (typeof (oDbg) != "undefined") { connectionConfig.oDbg = oDbg; } var connection = new JSJaCHttpBindingConnection(connectionConfig); remote.connection = connection; // 安装(注册)Connection事件模型 remote.jsjac.chat.setupEvent(connection); // setup args for connect method if (loginForm) { //connectionConfig = new Object(); //connectionConfig.domain = loginForm.domain.value; connectionConfig.username = loginForm.userName.value; connectionConfig.pass = loginForm.password.value; connectionConfig.register = loginForm.register.checked; } // 连接服务器 connection.connect(connectionConfig); //remote.jsjac.chat.changeStatus("available", "online", 1, "chat"); } catch (e) { remote.console.errorEL().html(e.toString()); } finally { return false; } }, // 改变用户状态 changeStatus: function (type, status, priority, show) { type = type || "unavailable"; status = status || "online"; priority = priority || "1"; show = show || "chat"; var presence = new JSJaCPresence(); presence.setType(type); // unavailable invisible if (remote.connection) { //remote.connection.send(presence); } //presence = new JSJaCPresence(); presence.setStatus(status); // online presence.setPriority(priority); // 1 presence.setShow(show); // chat if (remote.connection) { remote.connection.send(presence); } }, // 为Connection注册事件 setupEvent: function (con) { var remoteChat = remote.jsjac.chat; con.registerHandler('message', remoteChat.handleMessage); con.registerHandler('presence', remoteChat.handlePresence); con.registerHandler('iq', remoteChat.handleIQ); con.registerHandler('onconnect', remoteChat.handleConnected); con.registerHandler('onerror', remoteChat.handleError); con.registerHandler('status_changed', remoteChat.handleStatusChanged); con.registerHandler('ondisconnect', remoteChat.handleDisconnected); con.registerIQGet('query', NS_VERSION, remoteChat.handleIqVersion); con.registerIQGet('query', NS_TIME, remoteChat.handleIqTime); }, // 发送远程消息 sendMessage: function (msg, to) { try { if (msg == "") { return false; } var user = ""; if (to) { if (!~to.indexOf("@")) { user += "@" + remote.jsjac.domain; to += "/" + remote.jsjac.resource; } else if (~to.indexOf("/")) { user = to.substr(0, to.indexOf("/")); } } else { // 向chat接收信息区域写消息 if (remote.jsjac.chat.writeReceiveMessage) { var html = "你没有指定发送者的名称"; alert(html); //remote.jsjac.chat.writeReceiveMessage(receiverId, "server", html, false); } return false; } var userJID = "u" + hex_md5(user); $("#" + userJID).find(remote.receiver).val(to); // 构建jsjac的message对象 var message = new JSJaCMessage(); message.setTo(new JSJaCJID(to)); message.setType("chat"); // 单独聊天,默认为广播模式 message.setBody(msg); // 发送消息 remote.connection.send(message); return false; } catch (e) { var html = "<div class='msg error''>Error: " + e.message + "</div>"; remote.console.info(html); return false; } }, // 退出、断开链接 logout: function () { var presence = new JSJaCPresence(); presence.setType("unavailable"); if (remote.connection) { remote.connection.send(presence); remote.connection.disconnect(); } }, errorHandler: function (event) { var e = event || window.event; remote.console.errorEL().html(e); if (remote.connection && remote.connection.connected()) { remote.connection.disconnect(); } return false; }, unloadHandler: function () { var con = remote.connection; if (typeof con != "undefined" && con && con.connected()) { // save backend type if (con._hold) { // must be binding (new JSJaCCookie("btype", "binding")).write(); } if (con.suspend) { con.suspend(); } } }, writeMessage: function (userJID, userName, content) { // 向chat接收信息区域写消息 if (remote.jsjac.chat.writeReceiveMessage && !!content) { remote.jsjac.chat.writeReceiveMessage(userJID, userName, content, false); } }, // 重新连接服务器 reconnection: function () { remote.jsjac.register = false; if (remote.connection.connected()) { remote.connection.disconnect(); } remote.jsjac.chat.login(); }, /* ########################### Handler Event ############################# */ handleIQ: function (aIQ) { var html = "<div class='msg'>IN (raw): " + aIQ.xml().htmlEnc() + "</div>"; remote.console.info(html); remote.connection.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED)); }, handleMessage: function (aJSJaCPacket) { var user = aJSJaCPacket.getFromJID().toString(); //var userName = user.split("@")[0]; //var userJID = "u" + hex_md5(user); var content = aJSJaCPacket.getBody(); var html = ""; html += "<div class=\"msg\"><b>消息来自 " + user + ":</b><br/>"; html += content.htmlEnc() + "</div>"; remote.console.info(html); $.WebIM.messageHandler(user, content); }, handlePresence: function (aJSJaCPacket) { var user = aJSJaCPacket.getFromJID(); var userName = user.toString().split("@")[0]; var html = "<div class=\"msg\">"; if (!aJSJaCPacket.getType() && !aJSJaCPacket.getShow()) { html += "<b>" + userName + " 上线了.</b>"; } else { html += "<b>" + userName + " 设置 presence 为: "; if (aJSJaCPacket.getType()) { html += aJSJaCPacket.getType() + ".</b>"; } else { html += aJSJaCPacket.getShow() + ".</b>"; } if (aJSJaCPacket.getStatus()) { html += " (" + aJSJaCPacket.getStatus().htmlEnc() + ")"; } } html += "</div>"; remote.console.info(html); // 向chat接收信息区域写消息 remote.jsjac.chat.writeMessage("", userName, html); }, handleError: function (event) { var e = event || window.event; var html = "An error occured:<br />" + ("Code: " + e.getAttribute("code") + "\nType: " + e.getAttribute("type") + "\nCondition: " + e.firstChild.nodeName).htmlEnc(); remote.error(html); var content = ""; switch (e.getAttribute("code")) { case "401": content = "登陆验证失败!"; break; // 当注册发现重复,表明该用户已经注册,那么直接进行登陆操作 case "409": //content = "注册失败!\n\n请换一个用户名!"; remote.jsjac.chat.reconnection(); break; case "503": content = "无法连接到IM服务器,请检查相关配置!"; break; case "500": var contents = "服务器内部错误!\n\n连接断开!<br/><a href='javascript: self.parent.remote.jsjac.chat.reconnection();'>重新连接</a>"; remote.jsjac.chat.writeMessage("", "系统", contents); break; default: break; } if (content) { alert("WeIM: " + content); } if (remote.connection.connected()) { remote.connection.disconnect(); } }, // 状态变化触发事件 handleStatusChanged: function (status) { remote.console.info("<div>当前用户状态: " + status + "</div>"); remote.dbger.log("当前用户状态: " + status); if (status == "disconnecting") { var html = "<b style='color:red;'>你离线了!</b>"; // 向chat接收信息区域写消息 remote.jsjac.chat.writeMessage("", "系统", html); } }, // 建立链接触发事件方法 handleConnected: function () { remote.console.clear("debug"); // reset remote.connection.send(new JSJaCPresence()); }, // 断开链接触发事件方法 handleDisconnected: function () { }, handleIqVersion: function (iq) { remote.connection.send(iq.reply([ iq.buildNode("name", remote.jsjac.resource), iq.buildNode("version", JSJaC.Version), iq.buildNode("os", navigator.userAgent) ])); return true; }, handleIqTime: function (iq) { var now = new Date(); remote.connection.send(iq.reply([ iq.buildNode("display", now.toLocaleString()), iq.buildNode("utc", now.jabberDate()), iq.buildNode("tz", now.toLocaleString().substring(now.toLocaleString().lastIndexOf(" ") + 1)) ])); return true; } }; ~~~ 这个文件的代码就是用jsjac库和openfire建立通信的核心代码,代码中已经有注释,这里我就不再赘述。如果有什么不懂的可以给我留言。 **4、消息区域、编辑器代码 send.message.editor-1.0.js** ~~~ /** * IM chat Send Message iframe editor * @author: hoojo * @email: hoojo_@126.com * @blog: http://blog.csdn.net/IBM_hoojo * @createDate: 2012-5-24 * @version 1.0 **/ var agent = window.navigator.userAgent.toLowerCase(); var sendMessageEditor = { // 获取iframe的window对象 getWin: function () { return /*!/firefox/.test(agent)*/false ? sendMessageEditor.iframe.contentWindow : window.frames[sendMessageEditor.iframe.name]; }, //获取iframe的document对象 getDoc: function () { return !/firefox/.test(agent) ? sendMessageEditor.getWin().document : (sendMessageEditor.iframe.contentDocument || sendMessageEditor.getWin().document); }, init: function (userJID) { //打开document对象,向其写入初始化内容,以兼容FireFox var doc = sendMessageEditor.getDoc(); doc.open(); var html = [ '<html>', '<head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace;}</style></head>', '<body jid="', userJID, '"></body>', '</html>'].join(""); doc.write(html); //打开document对象编辑模式 doc.designMode = "on"; doc.close(); }, getContent: function () { var doc = sendMessageEditor.getDoc(); //获取编辑器的body对象 var body = doc.body || doc.documentElement; //获取编辑器的内容 var content = body.innerHTML; //对内容进行处理,例如替换其中的某些特殊字符等等 //Some code //返回内容 return content; }, //统一的执行命令方法 execCmd: function (cmd, value, d){ var doc = d || sendMessageEditor.getDoc(); //doc对象的获取参照上面的代码 //调用execCommand方法执行命令 doc.execCommand(cmd, false, value === undefined ? null : value); }, getStyleState: function (cmd) { var doc = sendMessageEditor.getDoc(); //doc对象的获取参考上面的对面 //光标处是否是粗体 var state = doc.queryCommandState(cmd); if(state){ //改变按钮的样式 } return state; }, insertAtCursor: function (text, d, w){ var doc = d || sendMessageEditor.getDoc(); var win = w || sendMessageEditor.getWin(); //win对象的获取参考上面的代码 if (/msie/.test(agent)) { win.focus(); var r = doc.selection.createRange(); if (r) { r.collapse(true); r.pasteHTML(text); } } else if (/gecko/.test(agent) || /opera/.test(agent)) { win.focus(); sendMessageEditor.execCmd('InsertHTML', text, doc); } else if (/safari/.test(agent)) { sendMessageEditor.execCmd('InsertText', text, doc); } } }; ~~~ **5、css样式 chat-2.0.css** ~~~ /** * function: im web chat css * author: hoojo * createDate: 2012-5-26 上午11:42:10 */ @CHARSET "UTF-8"; *, body { font-family: Courier,serif,monospace; font-size: 12px; padding: 0; margin: 0; } .chat-main { position: absolute; /*right: 80px;*/ left: 50px; top: 20px; z-index: 999; display: none; } .chat-main .radius { background-color: white; border: 8px solid #94CADF; border-radius: 1em; } #chat { position: relative; /*left: 150px;*/ padding: 0; margin: 0; } #chat table { border-collapse: collapse; width: 435px; *width: 460px; /*width: 410px;*/ /*width: 320px;*/ } #chat table .title { font-weight: bold; color: green; padding: 3px; background-color: #94CADF; } /* 收缩条 */ #chat table .split { background-color: #94CADF; cursor: pointer; } /* ################## product info #################### */ #chat table .product-info { width: 30%; /*display: none;*/ padding: 0; margin: 0; vertical-align: top; } #chat table .product-info ul { margin: 0; padding: 0; } #chat table .product-info ul div.header { background-color: #EBEFFE; line-height: 22px; font-size: 12px; color: black; } #chat table .product-info ul li { list-style: none outside none; background-color: white; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; padding-left: 5px; line-height: 22px; font-size: 11px; color: #6F6F6F; width: 140px; } #chat table .product-info ul li.pic { height: 200px; padding: 0 5px 0 5px; border: 1px dashed #ccc; text-align: center; } #chat table .product-info ul li.pic img { } #chat table .product-info ul li.product-name { font-weight: bold; color: black; } #chat table .product-info ul li.price span { font-family: Courier; font-size: 16px; font-weight: bold; color: #ED4E08; } #chat table .product-info ul li.market-price s { color: black; } #chat table .product-info ul li a { float: right; } #chat table .product-info ul li.info { display: none; } /*########### 接收消息区域 ############ */ #chat table .receive-message { height: 250px; } #chat table .send-message { width: 100%; /*height: auto;*/ } #chat table td { /*border: 1px solid white;*/ } #chat table .bottom-bar { background-color: #94CADF; text-align: right; } /* ############## 工具条 ################# start */ #chat table .tool-bar { height: 25px; background-color: #94CADF; } #chat table .tool-bar select { float: left; } #chat table .tool-bar select.family { width: 45px; *width: 55px; } #chat table .tool-bar div { width: 17px; height: 16px; float: left; cursor: pointer; margin-right: 2px; margin-top: 1px; *margin-top: 2px; background: transparent url("../images/tb-sprite.gif") no-repeat scroll 0 0; } #chat table .tool-bar .color { margin-left: 2px; background-position: -159px 0; } #chat table .tool-bar .bold { /*background-position: 0 0;*/ } #chat table .tool-bar .italic { background-position: -18px 0; } #chat table .tool-bar .underline { background-position: -32px 0; } #chat table .tool-bar .face { margin: 2px 0 0 3px; background-image: url("../images/facehappy.gif"); } #chat table .tool-bar .history { background-image: none; width: 60px; float: right; margin-top: 3px; font-size: 12px; display: none; } /* ###### 表情 ###### */ #chat #face { border: 1px solid black; width: 275px; *width: 277px; position: relative; left: 8px; top: -370px; _top: -359px; z-index: 3; display: none; } #chat #face img { border: 1px solid #ccc; border-right: none; border-bottom: none; cursor: pointer; } #send { width: 90px; height: 25px; } #close { width: 40px; height: 25px; } .chat-message { position: absolute; bottom: 0; left: 0; width: 100%; height: 25px; background-color: #fcfcfc; } .no-msg, .have-msg { cursor: pointer; float: right; margin: 5px 5px 0 0; } ~~~ **6、web.xml配置** ~~~ <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>Jabber HTTP Binding Servlet</servlet-name> <servlet-class>org.jabber.JabberHTTPBind.JHBServlet</servlet-class> <!-- <init-param> <param-name>debug</param-name> <param-value>1</param-value> </init-param> --> </servlet> <servlet-mapping> <servlet-name>Jabber HTTP Binding Servlet</servlet-name> <url-pattern>/JHB/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ~~~ 至此,这个应用的全部代码已经贴出来,如果你按照我这边的结构形式应该是可以完成这个聊天应用的。如果你有什么问题或想法,欢迎你给我留言或评论!
';

jQuery 获取屏幕高度、宽度

最后更新于:2022-04-01 10:05:20

~~~ 做手机Web开发做浏览器兼容用到了,所以在网上找了些汇总下。 alert($(window).height()); //浏览器当前窗口可视区域高度 alert($(document).height()); //浏览器当前窗口文档的高度 alert($(document.body).height());//浏览器当前窗口文档body的高度 alert($(document.body).outerHeight(true));//浏览器当前窗口文档body的总高度 包括border padding margin alert($(window).width()); //浏览器当前窗口可视区域宽度 alert($(document).width());//浏览器当前窗口文档对象宽度 alert($(document.body).width());//浏览器当前窗口文档body的高度 alert($(document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度 包括border padding margin // 获取页面的高度、宽度 function getPageSize() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else { if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if (document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else { if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else { if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } } } // for small pages with total height less then height of the viewport if (yScroll < windowHeight) { pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if (xScroll < windowWidth) { pageWidth = xScroll; } else { pageWidth = windowWidth; } arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight); return arrayPageSize; } // 滚动条 document.body.scrollTop; $(document).scrollTop(); ~~~
';

jquery blockUI 扩展插件 Dialog

最后更新于:2022-04-01 10:05:17

对jQuery blockUI插件进行了小的封装扩展,支持confirm、alert、dialog弹出窗口提示信息,支持按钮回调事件。可以自定义css样式、覆盖blockUI的样式等 首先要到jquery blockUI 官方网址:[http://malsup.com/jquery/block/](http://malsup.com/jquery/block/) 下载jquery.blockUI JS lib:[http://malsup.com/jquery/block/jquery.blockUI.js?v2.38](http://malsup.com/jquery/block/jquery.blockUI.js?v2.38) 而且还需要jquery lib:[http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js](http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js) jquery.blockUI.dialog.js ~~~ /*** * jquery blockUI Dialog plugin * v1.1 * @createDate -- 2012-1-4 * @author hoojo * @email hoojo_@126.com * @requires jQuery v1.2.3 or later, jquery.blockUI-2.3.8 * Copyright (c) 2012 M. hoo * Dual licensed under the MIT and GPL licenses: * http://hoojo.cnblogs.com * http://blog.csdn.net/IBM_hoojo **/ ;(function ($) { var _dialog = $.blockUI.dialog = {}; // dialog 默认配置 var defaultOptions = { css: { padding: '8px', opacity: .7, color: '#ffffff', border: 'none', 'border-radius': '10px', backgroundColor: '#000000' }, // 默认回调函数 取消或隐藏 dialog emptyHandler: function () { $.unblockUI(); }, // 用户回调函数 callbackHandler: function (fn) { return function () { fn(); defaultOptions.emptyHandler(); }; }, // confirm 提示 html元素 confirmElement: function (settings) { settings = settings || {}; var message = settings.message || "default confirm message!"; var okText = settings.okText || "ok"; var cancelText = settings.cancelText || "cancel"; if (typeof settings.onOk !== "function") { settings.onOk = this.emptyHandler; } if (typeof settings.onCancel !== "function") { settings.onCancel = this.emptyHandler; } var okCallback = this.callbackHandler(settings.onOk) || this.emptyHandler; var cancelCallback = this.callbackHandler(settings.onCancel) || this.emptyHandler; var html = [ '<div class="dialog confirm">', '<p>', message, '</p>', '<input type="button" value="', okText, '" class="btn ok-btn"/>', '<input type="button" value="', cancelText, '" class="btn cancel-btn"/>' ].join(""); var $el = $(html); $el.find(":button").get(0).onclick = okCallback; $el.find(":button:last").get(0).onclick = cancelCallback; return $el; }, // alert 提示html元素 alertElement: function (settings) { settings = settings || {}; var message = settings.message || "default alert message!"; var okText = settings.okText || "ok"; if (typeof settings.onOk !== "function") { settings.onOk = this.emptyHandler; } var okCallback = this.callbackHandler(settings.onOk) || this.emptyHandler; var html = [ '<div class="dialog alert">', '<p>', message, '</p>', '<input type="button" value="', okText, '" class="btn ok-btn"/>' ].join(""); var $el = $(html); $el.find(":button:first").get(0).onclick = okCallback; return $el; } }; var _options = defaultOptions; // 对外公开的dialog提示html元素,提供配置、覆盖 $.blockUI.dialog.confirmElement = function () { return _options.confirmElement(arguments[0]); }; $.blockUI.dialog.alertElement = function () { return _options.alertElement(arguments[0]); }; // 提供jquery 插件方法 $.extend({ confirm: function (opts) { var i = (typeof opts === "object") ? 1 : 0; var defaults = { message: arguments[i++] || "default confirm message!", onOk: arguments[i++] || _options.emptyHandler(), onCancel: arguments[i++] || _options.emptyHandler(), okText: arguments[i++] || "ok", cancelText: arguments[i] || "cancel" }; opts = opts || {}; opts.css = $.extend({}, _options.css, opts.css); // 覆盖默认配置 var settings = $.extend({}, _options, defaults, opts); settings = $.extend(settings, { message: _dialog.confirmElement(settings) }); settings = $.extend({}, $.blockUI.defaults, settings); $.blockUI(settings); }, alert: function (opts) { var i = (typeof opts === "object") ? 1 : 0; var defaults = { message: arguments[i++] || "default alert message!", onOk: arguments[i++] || _options.emptyHandler(), okText: arguments[i] || "ok" }; opts = opts || {}; opts.css = $.extend({}, _options.css, opts.css); var settings = $.extend({}, _options, defaults, opts); settings = $.extend(settings, { message: _dialog.alertElement(settings) }); settings = $.extend({}, $.blockUI.defaults, settings); $.blockUI(settings); }, // dialog提示 dialog: function (opts) { var settings = $.extend({}, $.blockUI.defaults, _options, opts || {}); $.blockUI(settings); }, // 移除dialog提示框 removeDialog: function () { _options.emptyHandler(); } }); })(jQuery); ~~~ 应用样式文件block.dialog.css dialog是全局样式,btn是所有按钮的样式、ok-btn是ok按钮样式、cancel-btn是取消按钮样式 ~~~ .dialog { font-size: 12px; } .dialog .btn { border: 1px solid white; border-radius: 5px; min-width: 25%; width: auto; } .dialog .ok-btn { background-color: #ccc; } .dialog .cancel-btn { /*background-color: #aeface;*/ margin-left: 10%; } ~~~ examples.html ~~~ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>blockUI Dialog Examples</title> <meta http-equiv="author" content="hoojo"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="blockUI/block.dialog.css" /> <script type="text/javascript" charset="UTF-8" src="mobile/jquery-1.6.4.js"></script> <script type="text/javascript" charset="UTF-8" src="blockUI/jquery.blockUI-2.3.8.js"></script> <script type="text/javascript" charset="UTF-8" src="blockUI/jquery.blockUI.dialog-1.1.js"></script> <script type="text/javascript"> ;(function ($) { $(function () { // dialog 提示框 $("#dialog").click(function () { //$.dialog(); //$.dialog({message: $("#callback")}); $.dialog({ //theme: true, // 设置主题需要jquery UI http://www.malsup.com/jquery/block/theme.html title: "dialog", message: $("#callback"), fadeIn: 1000, fadeOut: 1200 }); setTimeout($.removeDialog, 2000); }); // 带确定、取消按钮提示框,支持事件回调,及message等属性配置 $("#confirm").click(function () { $.confirm({ message: "你确定要删除吗?", okText: "确定", cancelText: "取消", onOk: function () { alert("你点击了确定按钮"); }, onCancel: function () { alert("你点击了取消按钮"); } }); }); // 警告提示框 对象模式配置css、message、按钮文本提示 $("#alert").click(function () { $.alert({ message: "你确定要删除吗?", okText: "确定", css: { "background-color": "white", "color": "red" }, onOk: function () { alert("你点击了确定按钮"); } }); }); // 非对象配置属性,多个参数配置 /** $.confirm 方法参数config配置介绍: 当第一个参数是一个对象: 对象中可以出现以下属性配置,并且可以出现$.blockUI的配置 { message: arguments[i++] || "default confirm message!", onOk: arguments[i++] || _options.emptyHandler(), onCancel: arguments[i++] || _options.emptyHandler(), okText: arguments[i++] || "ok", cancelText: arguments[i] || "cancel" } message 是提示框的提示信息 onOk是确定按钮的click回调函数 onCancel 是取消按钮的click事件回调方法 okText是ok按钮的文字 默认是ok cancelText是cancel按钮的文本内容 如果第一个参数不是一个对象,那么 参数1表示 message 及提示文字 参数2表示ok按钮的click事件回调函数 参数3表示cancel按钮的click事件回调函数 参数4表示ok按钮的文本 参数5表示cancel按钮的文本内容 注意:如果第一参数是一个对象,后面又出现了相应的参数配置;这种情况下对象配置优先于 后面的参数配置,而且参数的位置也会改变: 参数1是对象配置 参数2表示 message 及提示文字 参数3表示ok按钮的click事件回调函数 参数4表示cancel按钮的click事件回调函数 参数5表示ok按钮的文本 参数6表示cancel按钮的文本内容 */ $("#confirm2").click(function () { $.confirm({ message: "is a message", timeout: 3000 }, "message", function () { alert("success"); }, function () { alert("failure"); }, "按钮"); }); /** 第一个参数是对象配置,当对象配置中出现的选项会覆盖后面的参数配置 $.alert 方法 config 介绍: 当第一个参数 是一个对象: { message: arguments[i++] || "default alert message!", onOk: arguments[i++] || _options.emptyHandler(), okText: arguments[i] || "ok" } message 是提示框的提示信息 onOk是确定按钮回调函数 okText是ok按钮的文字 默认是ok 当第一个参数不是一个对象的情况下,那么 参数1表示 message 及提示文字 参数2表示ok按钮的click事件 参数3表示ok按钮的文本 注意:如果第一个参数是一个对象,对象中出现的配置:message、onOk、okText,这些配置将会 覆盖后面的配置,也就是说这些配置在第一个参数中出现后,后面的参数就不需要 */ $("#alert2").click(function () { $.alert({ css: { "background-color": "red" }, timeout: 1200, onOk: function () { alert("确定"); } }, "你有一条消息", function () { alert("被覆盖"); }, "yes?"); }); var _confirm = function (msg) { $.confirm({ message: msg, onOk: function () { alert("你点击了确定按钮"); }, onCancel: function () { alert("你点击了取消按钮"); } }); }; $("#confirm3").click(function () { _confirm("message"); }); var _alert = function (msg) { $.alert({ message: msg, css: { "background-color": "white", "color": "red" }, onOk: function () { alert("你点击了确定按钮"); } }); } $("#alert3").click(function () { _alert(); }); }); })(jQuery); </script> </head> <body> <ul> <h2>jQuery blockUI Dialog Demos</h2> <li>dialog demo <input type="button" value="dialog" id="dialog"/></li> <li>confirm callback demos<input type="button" value="confirm" id="confirm"/></li> <li>confirm callback demos 2<input type="button" value="confirm" id="confirm2"/></li> <li>confirm callback demos 3<input type="button" value="confirm" id="confirm3"/></li> <li>alert callback demos<input type="button" value="alert" id="alert"/></li> <li>alert callback demos 2<input type="button" value="alert" id="alert2"/></li> <li>alert callback demos 3<input type="button" value="alert" id="alert3"/></li> </ul> <div style="display: none;"> <div id="callback"> <p>ok or cancel? asdfaf jQuery blockUI Dialog Demos jQuery blockUI Dialog Demos jQuery blockUI Dialog Demos jQuery blockUI Dialog Demos</p> <input type="button" value="OK" class="btn ok-btn"/> <input type="button" value="Cancel" class="btn cancel-btn"/> </div> </div> </body> </html> ~~~ 截图效果 confirm ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d7399d2.gif) alert ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d752b40.gif)
';

jQuery autocomplete 自扩展插件、自动补全示例

最后更新于:2022-04-01 10:05:15

jquery-lib版本是 1.3.2的,该插件是简单的扩展插件,代码也比较简单的封装。所以看起来也比较简单不是很费力,当然封装得也不是很好。 不过做了浏览器方面的兼容,经测试兼容IE6+、Firefox3.5+ 首先看看autocomplete.js: ~~~ ;(function ($) { var index = -1; var timeId; var cssOptions = { "border": "1px solid black", "background-color": "white", "position": "absolute"/*, "font": "normal normal lighter 14px 6px Times New Roman"*/ }; var defaults = { width: "auto", highlightColor: "#3399FE", unhighlightColor: "#FFFFFF", css: cssOptions, dataType: "xml", paramName: "word", delay: 500, max: 20 }; var keys = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, ENTER: 13, ESC: 27, /*COMMA: 188,*/ PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8, A: 65, Z: 90 }; $.fn.extend({ autocomplete: function (sUrl, settings) { sUrl = (typeof sUrl === "string") ? sUrl : ""; var param = !this.attr("id") ? defaults.paramName : this.attr("id"); settings = $.extend({}, defaults, {url: sUrl, paramName: param}, settings); var autoTip = this.autoTipTemplate(this, settings); $("body").append(autoTip); var $this = this; this.keyup(function (event) { $this.keyOperator(event, autoTip, settings); }); /*$("input[type=button]").click(function () { $("#result").text("文本框中的【" + search.val() + "】被提交了!"); $("#auto").hide(); index = - 1; });*/ return this.each(function () { $this.val(); }); }, autoTipTemplate: function (input, settings) { var inputOffset = input.offset(); var autoTip = $("<div/>").css(settings.css).hide() .css("top", inputOffset.top + input.height() + 5 + "px") .css("left", inputOffset.left + "px"); var space = $.browser.mozilla ? 2 : 6;//兼容浏览器 var tipWidth = (typeof settings.width === "string" && "auto") ? input.width() : settings.width; autoTip.width(tipWidth + space + "px"); return autoTip; }, select: function (target, index, settings, flag) { var color = flag ? settings.highlightColor : settings.unhighlightColor; target.children("div").eq(index).css("background-color", color); }, keyOperator: function (event, autoTip, settings) { var evt = event || window.event; var autoNodes = autoTip.children("div"); var kc = evt.keyCode; var $this = this; /* 当用户按下字母或是delete 或是退格键*/ if (kc >= keys.A && kc <= keys.Z || kc == keys.BACKSPACE || kc == keys.DEL) { var wordText = this.val(); if (wordText.length != 0) { var param = {}; param[settings.paramName] = wordText; clearTimeout(timeId); timeId = setTimeout(function () { $.post(settings.url, param, function (data) { var wordObj = $(data); if (settings.dataType == "xml") { var wordNodes = wordObj.find("word"); autoTip.html(""); wordNodes.each(function (i) { var divNode = $("<div>").attr("id", i); //将遍历的单词加入到创建的div中,然后把该div追加到auto中 divNode.html($(this).text()).appendTo(autoTip); //鼠标已进去,添加高亮 divNode.mousemove(function () { //如果已经存在高亮,去掉高亮改为白色 if (index != -1) { autoTip.children("div").eq(index).css("background-color", settings.unhighlightColor); } index = $(this).attr("id"); $(this).css("background-color", settings.highlightColor); }); //鼠标移出,取消高亮 divNode.mouseout(function () { $(this).css("background-color", settings.unhighlightColor); }); //点击高亮内容 divNode.click(function () { $this.val($(this).text()); index = -1; autoTip.hide(); }); }); if (wordNodes.length > 0) { autoTip.show(); } else { autoTip.hide(); index = -1; } } }); }, settings.delay); } else { autoTip.hide(); index = -1; } } else if (kc == keys.UP || kc == keys.DOWN) {/*当用户按下上下键*/ if (kc == keys.UP) {//向上 if (index != -1) { autoNodes.eq(index).css("background-color", settings.unhighlightColor); index--; } else { index = autoNodes.length - 1; } if (index == -1) { index = autoNodes.length - 1; } autoNodes.eq(index).css("background-color", settings.highlightColor); } else {//向下 if (index != -1) { autoNodes.eq(index).css("background-color", settings.unhighlightColor); } index++; if (index == autoNodes.length) { index = 0; } autoNodes.eq(index).css("background-color", settings.highlightColor); } } else if (kc == keys.PAGEUP || kc == keys.PAGEDOWN) { event.preventDefault(); if (kc == keys.PAGEUP) { if (index != -1) { autoNodes.eq(index).css("background-color", settings.unhighlightColor); } if (autoNodes.length > 0) { index = 0; autoNodes.eq(0).css("background-color", settings.highlightColor); } } else { if (index != -1) { autoNodes.eq(index).css("background-color", settings.unhighlightColor); } index = autoNodes.length - 1; autoNodes.eq(index).css("background-color", settings.highlightColor); } } else if (kc == keys.ENTER) { //回车键 //有高亮内容就补全信息 if (index != -1) { $this.val(autoNodes.eq(index).text()); } else {//没有就隐藏 $("body").append($("<div/>").text("文本框中的【" + $this.val() + "】被提交了!")); $this.get(0).blur(); } autoTip.hide(); index = -1; } else if (kc == keys.ESC) { autoTip.hide(); } } }); })(jQuery); ~~~ 现在来分析上面的autocomplete插件的一些常用选项: index就是选择提示选项高亮的索引; timeId是当用户在文本域输入时,利用setTimeout进行ajax请求服务器获得数据的而返回的时间; cssOptions是自动提示选项的样式,这里给出了一些默认的样式; ~~~ var defaults = {         width: "auto",//默认或自动设置宽度         highlightColor: "#3399FE",//高亮时的颜色         unhighlightColor: "#FFFFFF",//非高亮时的颜色         css: cssOptions,         dataType: "xml",//ajax请求返回数据类型         paramName: "word",//ajax请求的参数名称,如果你有设置文本域的id,那么就使用这个属性         delay: 500,//当文本域在不停的输入时,ajax多久请求一次服务器     }; ~~~ keys就是键盘键对应的值; autocomplete就是调用的函数,可以在里面设置ajax请求的url,以及配置上面defaults中出现的参数,这个方法返回的是文本域的值; autoTipTemplate就是输入时显示的提示框、提示菜单,返回的是一个jquery对象; select是选择提示菜单也就是下来提示菜单的高亮选项,target当然是目标对象了,index是即将被高亮的选项的索引,settings就是 高亮的颜色配置,这个在默认defaults中就有的。是通过$.extend方法将defaults对象的属性赋值给settings对象的; keyOperator是针对文本域的键盘操作,这个是核心函数;操作提示、自动补全就靠它了;   下面看看html代码,看看是如何调用autocomplete插件的: ~~~ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Ajax示例,实现Google搜索补全功能</title> <meta http-equiv="author" content="hoojo"> <meta http-equiv="email" content="hoojo_@126.com"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="jslib/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jslib/jquery.autocomplete-1.2.js"></script> <script type="text/javascript"> $(function () { $(":text").autocomplete("AutocompleteWordServlet", {dataType: "xml", width: "auto"}); }); </script> </head> <body> 请输入:<input type="text" /> <input type="button" value="Go" /><br/><br/> </body> </html> ~~~   看看这段代码AutocompleteWordServlet是请求的Servlet,dataType是ajax请求服务器端的返回数据的类型,width可以设置自动提示菜单的宽度。 怎么样,用法比较简单吧。当然后面你还可以加其他的配置,如: 代码片段 ~~~ $(":text").autocomplete("AutocompleteWordServlet", { width: "auto", highlightColor: "#3355FE", unhighlightColor: "#FFFFcc", css: {border: "2px solid red"}, dataType: "xml", paramName: "keyWord", delay: 300 }); ~~~ 这样也是可以的; 看看AutocompleteWordServlet的代码: ~~~ package com.hoo.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class AutocompleteWordServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String word = request.getParameter("word"); request.setAttribute("word", word); //System.out.println(word); request.getRequestDispatcher("word.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ~~~ 没什么可说的,就是获取客户端文本域的ajax请求的关键字,然后在jsp页面中进行单词过滤。不过你也可以在客户端用正则 或是在服务器端用正则过滤都是可以的。 下面看看word.jsp的内容: ~~~ <%@ page language="java" contentType="text/xml; charset=UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <words> <c:if test="${fn:startsWith('abstruct', word)}"> <word>abstruct</word> </c:if> <c:if test="${fn:startsWith('anilazine', word)}"> <word>anilazine</word> </c:if> <c:if test="${fn:startsWith('appeared', word)}"> <word>appeared</word> </c:if> <c:if test="${fn:startsWith('autocytolysis', word)}"> <word>autocytolysis</word> </c:if> <c:if test="${fn:startsWith('apple', word)}"> <word>apple</word> </c:if> <c:if test="${fn:startsWith('boolean', word)}"> <word>boolean</word> </c:if> <c:if test="${fn:startsWith('break', word)}"> <word>break</word> </c:if> <c:if test="${fn:startsWith('bird', word)}"> <word>bird</word> </c:if> <c:if test="${fn:startsWith('blur', word)}"> <word>blur</word> </c:if> <c:if test="${fn:startsWith('call', word)}"> <word>call</word> </c:if> <c:if test="${fn:startsWith('class', word)}"> <word>class</word> </c:if> <c:if test="${fn:startsWith('card', word)}"> <word>card</word> </c:if> <c:if test="${fn:startsWith('dacnomania', word)}"> <word>dacnomania</word> </c:if> <c:if test="${fn:startsWith('document', word)}"> <word>document</word> </c:if> </words> ~~~ 就是一个xml格式的文档,通过使用jstl表达式,用startsWith函数匹配,如果通过就显得在xml内容中,还有看到上面的contentType="text/xml; charset=UTF-8"了没有,是text/xml哦!这点要注意,如果不设置有的浏览器就不能解析了。
';

jquery tab 选项卡功能

最后更新于:2022-04-01 10:05:13

~~~ jquery选项卡,带css样式的。支持ajax更新内容、页面同时出现多个tab选项卡而不影响其他选项卡内容。 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>jquery tab 选项卡</title> <meta http-equiv="author" content="hoojo"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> .tab { background-color: mintcream; width: 200px; -width: 205px; height: 200px; margin-left: 200px; } .header { height: 20px; width: 100%; } .content { border: 1px solid #CCCCFF; border-top: none; height: 180px; } .liStyle { cursor: pointer; height: 20px; width: 66px; -width: 61px; float: left; background-color: white; } .show { background-color: mintcream; border: 1px solid #CCCCFF; border-bottom: none; } .hide { background-color: white; border-bottom: 1px solid #CCCCFF; } .ulHide { display: none; } .ulShow { display: block; } ul { list-style: none outside none; } * { margin: 0; padding: 0; } </style> <script type="text/javascript"> $(function () { $(".tab > ul.header > li").click(function () { $(this).parent().find("li.show").addClass("hide").removeClass("show"); $(this).addClass("show").removeClass("hide"); var parentsEl = $(this).parents(".tab"); parentsEl.find("div > ul.ulShow").addClass("ulHide").removeClass("ulShow"); /*页面静态内容*/ var ary = parentsEl.find("ul.header > li"); parentsEl.find("div > ul:eq(" + $.inArray(this, ary) + ")").addClass("ulShow").removeClass("ulHide"); /*用ajax动态加载内容 parentsEl.find("div > ul:eq(" + $.inArray(this, ary) + ")").addClass(function () { var el = this; $.post("TreeDataServlet", {param: "params"}, function (data) { $(el).html(data); }); return "ulShow"; }).removeClass("ulHide");*/ }) }); </script> </head> <body bgcolor="white"> <div class="tab"> <ul class="header"> <li class="liStyle show">Java</li> <li class="liStyle hide">Spring</li> <li class="liStyle hide">Hibernate</li> </ul> <div class="content"> <ul class="ulShow"> Java <li>java javaSE</li> <li>java javaME</li> <li>java javaEE</li> </ul> <ul class="ulHide"> Spring <li>java springMVC</li> <li>java spring aop</li> <li>java spring Ioc DI</li> </ul> <ul class="ulHide"> Hibernate <li>java Hibernate Configuration Transaction</li> <li>java Hibernate Query Criteria</li> <li>java Hibernate Session SessionFactory</li> </ul> </div> </div> <hr/> <div class="tab"> <ul class="header"> <li class="liStyle show">Java</li> <li class="liStyle hide">Spring</li> <li class="liStyle hide">Hibernate</li> </ul> <div class="content"> <ul class="ulShow"> Java.... <li>java javaSE</li> <li>java javaME</li> <li>java javaEE</li> </ul> <ul class="ulHide"> Spring.... <li>java springMVC</li> <li>java spring aop</li> <li>java spring Ioc DI</li> </ul> <ul class="ulHide"> Hibernate.... <li>java Hibernate Configuration Transaction</li> <li>java Hibernate Query Criteria</li> <li>java Hibernate Session SessionFactory</li> </ul> </div> </div> </body> </html> ~~~
';

extJS checkBoxColunmTree 可以选择带checkBox的树(tree、grid)

最后更新于:2022-04-01 10:05:10

**checkBoxColunmTree.html** 可以选择节点的多列的树,也可以说是可以分组选择的grid。既是tree也是grid。 column-tree.css这个文件在ext2.2版本中的ext-2.2/examples/tree这个目录下会找到这个文件的。 ~~~ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>checkBoxColunmTree.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" /> <link rel="stylesheet" type="text/css" href="ext/resources/css/column-tree.css" /> <script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="ext/ext-all.js"></script> <script type="text/javascript" src="ext/ColumnTree.js"></script> <script type="text/javascript"> Ext.onReady(function () { Ext.BLANK_IMAGE_URL = 'ext/resources/images/default/s.gif'; var tree = new Ext.tree.ColumnTree({ width:568, height:300, border: false, lines: false, animate: false, rootVisible: false, autoScroll:true, checkModel:'cascade',//级联多选,如果不需要checkbox,该属性去掉 onlyLeafCheckable: false,//所有结点可选,如果不需要checkbox,该属性去掉 loader: new Ext.tree.TreeLoader({ dataUrl: '../TreeDataServlet',//'column-data.json', uiProviders:{ 'col': Ext.ux.ColumnTreeCheckNodeUI//如果不需要checkbox,则需要使用Ext.tree.ColumnTreeNodeUI } }), columns:[ { header:'商品名称', width:170, dataIndex:'commodityName'}, { header:'编号', width:70, dataIndex:'id'}, { header:'代理/公司', width:180, dataIndex:'proxyName' }, { header:'价格', width:70, dataIndex:'price'} ], root: new Ext.tree.AsyncTreeNode({ text: '代理/公司' }), tbar:['公司名称:',{xtype:'textfield',id:'proxyName'},'商品名称:',{xtype:'textfield',id:'commodityName'},{text:'查询'}] }); var win = new Ext.Window({ title: 'Example column tree', width:582, height:388, border :true, resizable : false, items: tree, buttonAlign:'center', buttons:[{text:'确定'},{text:'关闭'}] }); win.show(); }); </script> </head> <body> </body> </html> ~~~ ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d6ae573.gif)   后台java代码 **TreeDataServlet.java** ~~~ package com.hoo.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TreeDataServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/text"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); StringBuffer resultStr = new StringBuffer(); resultStr.append("[{"); resultStr.append("id: ' 10000',"); resultStr.append("commodityName: '微软鼠标',"); resultStr.append("uiProvider: 'col',"); //得到group 值 resultStr.append("children: [{"); resultStr.append("id: ' 100000',"); resultStr.append("proxyName: '微软代理商-中国代理 联强 ',"); resultStr.append("commodityName: 'IO 1.0',"); resultStr.append("price: '198.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'},"); resultStr.append("{id: ' 100000',"); resultStr.append("proxyName: '微软代理商-中国代理 联强 ',"); resultStr.append("commodityName: 'IE 3.0',"); resultStr.append("price: '298.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'},"); resultStr.append("{id: ' 100000',"); resultStr.append("proxyName: '微软代理商-中国代理 联强 ',"); resultStr.append("commodityName: 'IO 2.0',"); resultStr.append("price: '200.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'"); resultStr.append("}]},{"); resultStr.append("id: ' 20000',"); resultStr.append("commodityName: '罗技鼠标',"); resultStr.append("uiProvider: 'col',"); //得到group 值 resultStr.append("children: [{"); resultStr.append("id: ' 100001',"); resultStr.append("proxyName: '罗技',"); resultStr.append("commodityName: 'max 500',"); resultStr.append("price: '298.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'},"); resultStr.append("{id: ' 100000',"); resultStr.append("proxyName: '罗技',"); resultStr.append("commodityName: 'max 518',"); resultStr.append("price: '298.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'},"); resultStr.append("{id: ' 100000',"); resultStr.append("proxyName: '罗技',"); resultStr.append("commodityName: 'max 520',"); resultStr.append("price: '245.00',"); resultStr.append("leaf:true,"); resultStr.append("uiProvider: 'col'"); resultStr.append("}]"); resultStr.append("}]"); out.print(resultStr.toString()); out.flush(); out.close(); } } ~~~ **ext/ColumnTree.js** 这个是扩展Ext.tree.ColumnTree的组件,只是添加了一个Ext.ux.ColumnTreeCheckNodeUI组件。有了这个组件我们才可以选择节点,所以这个是必须的; ~~~ /* * Ext JS Library 2.0 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ Ext.tree.ColumnTree = Ext.extend(Ext.tree.TreePanel, { //lines:false, borderWidth: Ext.isBorderBox ? 0 : 2, // the combined left/right border for each cell cls:'x-column-tree', scrollOffset : 18, onRender : function(){ Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments); this.headers = this.body.createChild( {cls:'x-tree-headers '},this.body.dom); var cols = this.columns, c; var totalWidth = 0; for(var i = 0, len = cols.length; i < len; i++){ c = cols[i]; totalWidth += c.width; this.headers.createChild({ cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''), cn: { cls:'x-tree-hd-text', html: c.header }, style:'width:'+(c.width-this.borderWidth)+'px;' }); } this.headers.createChild({ cls:'x-tree-hd ', cn: { html: '' }, style:'width:'+this.scrollOffset+'px;' }); totalWidth += this.scrollOffset; this.headers.createChild({cls:'x-clear'}); // prevent floats from wrapping when clipped this.headers.setWidth(totalWidth); totalWidth -= this.scrollOffset; this.innerCt.setWidth(totalWidth); } }); Ext.tree.ColumnTreeNodeUI = Ext.extend(Ext.tree.TreeNodeUI, { focus: Ext.emptyFn, // prevent odd scrolling behavior renderElements : function(n, a, targetNode, bulkRender){ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : ''; var t = n.getOwnerTree(); var cols = t.columns; var bw = t.borderWidth; var c = cols[0]; var cb = typeof a.checked == 'boolean'; if(typeof this.checkModel != 'undefined'){ cb = (!this.onlyLeafCheckable || n.isLeaf()); } var href = a.href ? a.href : Ext.isGecko ? "" : "#"; var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">', '<div class="x-tree-col" style="width:',c.width-bw,'px;">', '<span class="x-tree-node-indent">',this.indentMarkup,"</span>", '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow">', '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on">', cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '', '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ', a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '>', '<span unselectable="on">', n.text || (a[c.dataIndex]?(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]):''),"&nbsp;</span></a>", "</div>"]; for(var i = 1, len = cols.length; i < len; i++){ c = cols[i]; buf.push('<div class="x-tree-col ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">', '<div class="x-tree-col-text">',(a[c.dataIndex]?(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]):''),"&nbsp;</div>", "</div>"); } buf.push('<div class="x-clear"></div>', '</div>', '<ul class="x-tree-node-ct" style="display:none;"></ul>', "</li>"); if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){ this.wrap = Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(), buf.join("")); }else{ this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf.join("")); } this.elNode = this.wrap.childNodes[0]; this.ctNode = this.wrap.childNodes[1]; var cs = this.elNode.firstChild.childNodes; this.indentNode = cs[0]; this.ecNode = cs[1]; this.iconNode = cs[2]; var index = 3; if(cb){ this.checkbox = cs[3]; index++; } this.anchor = cs[index]; this.textNode = cs[index].firstChild; } }); //这个组件是扩展的,加入这个组件即可 Ext.ux.ColumnTreeCheckNodeUI = function() { //多选: 'multiple'(默认) //单选: 'single' //级联多选: 'cascade'(同时选父和子);'parentCascade'(选父);'childCascade'(选子) this.checkModel = 'multiple'; //only leaf can checked this.onlyLeafCheckable = false; Ext.ux.ColumnTreeCheckNodeUI.superclass.constructor.apply(this, arguments); }; Ext.extend(Ext.ux.ColumnTreeCheckNodeUI, Ext.tree.ColumnTreeNodeUI, { renderElements : function(n, a, targetNode, bulkRender){ var t = n.getOwnerTree(); this.checkModel = t.checkModel || this.checkModel; this.onlyLeafCheckable = t.onlyLeafCheckable || false; Ext.ux.ColumnTreeCheckNodeUI.superclass.renderElements.apply(this, arguments); var cb = (!this.onlyLeafCheckable || n.isLeaf()); if(cb){ Ext.fly(this.checkbox).on('click', this.check.createDelegate(this,[null])); } }, // private check : function(checked){ var n = this.node; var tree = n.getOwnerTree(); this.checkModel = tree.checkModel || this.checkModel; if( checked === null ) { checked = this.checkbox.checked; } else { this.checkbox.checked = checked; } n.attributes.checked = checked; tree.fireEvent('check', n, checked); if(!this.onlyLeafCheckable){ if(this.checkModel == 'cascade' || this.checkModel == 'parentCascade'){ var parentNode = n.parentNode; if(parentNode !== null) { this.parentCheck(parentNode,checked); } } if(this.checkModel == 'cascade' || this.checkModel == 'childCascade'){ if( !n.expanded && !n.childrenRendered ) { n.expand(false,false,this.childCheck); }else { this.childCheck(n); } } } else if(this.checkModel == 'single'){ var checkedNodes = tree.getChecked(); for(var i=0;i<checkedNodes.length;i++){ var node = checkedNodes[i]; if(node.id != n.id){ node.getUI().checkbox.checked = false; node.attributes.checked = false; tree.fireEvent('check', node, false); } } } }, // private childCheck : function(node){ var a = node.attributes; if(!a.leaf) { var cs = node.childNodes; var csui; for(var i = 0; i < cs.length; i++) { csui = cs[i].getUI(); if(csui.checkbox.checked ^ a.checked) csui.check(a.checked); } } }, // private parentCheck : function(node ,checked){ var checkbox = node.getUI().checkbox; if(typeof checkbox == 'undefined')return ; if(!(checked ^ checkbox.checked))return; if(!checked && this.childHasChecked(node))return; checkbox.checked = checked; node.attributes.checked = checked; node.getOwnerTree().fireEvent('check', node, checked); var parentNode = node.parentNode; if( parentNode !== null){ this.parentCheck(parentNode,checked); } }, // private childHasChecked : function(node){ var childNodes = node.childNodes; if(childNodes || childNodes.length>0){ for(var i=0;i<childNodes.length;i++){ if(childNodes[i].getUI().checkbox.checked) return true; } } return false; }, toggleCheck : function(value){ var cb = this.checkbox; if(cb){ var checked = (value === undefined ? !cb.checked : value); this.check(checked); } } }); ~~~
';

共享你的jquery 插件

最后更新于:2022-04-01 10:05:08

与他人共享你的插件,并将它上传到 jQuery 网站的插件存储库。 • 转到 jQuery 网站的插件页面,在左导航栏,单击 Login/Register 然后单击 Create New Account。如果已经有一个帐户,请登录;如果没有,则创建一个新帐户。 • 验证通过后,左导航将出现一些选项。其中有一个 “Add plug-in”。 • 导航插件创建页面。因为您只能使用 jQuery 1.2 测试该插件,您应该将其作为一个兼容版本包含在内。花一些时间为插件写一个好标题以及一个好的描述。毕竟,现在是向其他用户推销该插件的时候了,您需要让自己与众不同。尽量讲出该插件的好处。 • 该插件需要您提供插件主页。虽然您创建了插件,但很可能没有插件主页。幸运的是,如果您没有自己的服务器保存插件,Google 很乐于为开源项目提供空间。我选择在 Google Code 中放置该插件。要建立自己的 Google Code 项目,只需要访问 code.google.com 然后按照注册流程注册即可。 • 按下 Submit 之后您的插件就创建好了!恭喜,您的插件现在是 jQuery 插件社区的一部分了,您现在正式成为开源项目的贡献者之一。给自己一个 5 星评级以奖励自己吧!因为您值得!
';

jQuery 中常用的插件列表

最后更新于:2022-04-01 10:05:06

### 文件上传(File upload)[![JQuery_001](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d643a90.gif)](http://images.cnblogs.com/cnblogs_com/Terrylee/WindowsLiveWriter/240jQuery_128F5/JQuery_001_6.gif) [Ajax File Upload](http://www.phpletter.com/Demo/AjaxFileUpload-Demo/). [jQUploader](http://www.pixeline.be/experiments/jqUploader/). [Multiple File Upload plugin](http://www.fyneworks.com/jquery/multiple-file-upload/).  [jQuery File Style](http://www.appelsiini.net/projects/filestyle). [Styling an input type file](http://jquery.com/plugins/project/InputFileCSS). [Progress Bar Plugin](http://digitalbush.com/projects/progress-bar-plugin). ### 表单验证(Form Validation) [jQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/). [Auto Help](http://www.dyve.net/jquery/?autohelp). [Simple jQuery form validation](http://www.willjessup.com/sandbox/jquery/form_validator/form_validate.html). [jQuery XAV - form validations](http://letmehaveblog.blogspot.com/2007/08/easy-client-side-web-forms-validations.html). [jQuery AlphaNumeric](http://itgroup.com.ph/alphanumeric/). [Masked Input](http://digitalbush.com/projects/masked-input-plugin). [TypeWatch Plugin](http://www.dennydotnet.com/post/TypeWatch-jQuery-Plugin.aspx). [Text limiter for form fields](http://jquery.com/plugins/project/TextLimiter). [Ajax Username Check with jQuery](http://www.shawngo.com/gafyd/index.html). ### 表单-选取框(Form - Select Box stuff) [jQuery Combobox](http://jquery.sanchezsalvador.com/page/jquerycombobox.aspx). [jQuery controlled dependent (or Cascadign) Select List](http://www.ajaxray.com/blog/2007/11/08/jquery-controlled-dependent-or-cascading-select-list-2/). [Multiple Selects](http://code.google.com/p/jqmultiselects/). [Select box manipulation](http://www.texotela.co.uk/code/jquery/select/). [Select Combo Plugin](http://code.google.com/p/jqueryselectcombo/). [jQuery - LinkedSelect](http://www.msxhost.com/jquery/linked-selects/json/%20target=) [Auto-populate multiple select boxes](http://remysharp.com/2007/09/18/auto-populate-multiple-select-boxes/). [Choose Plugin (Select Replacement)](http://www.sitespotting.it/esempi/002/). ### 表单基本、输入框、选择框等(Form Basics, Input Fields, Checkboxes etc.) [jQuery Form Plugin](http://www.malsup.com/jquery/form/). [jQuery-Form](http://code.handlino.com/wiki/jquery-form). [jLook Nice Forms](http://envero.org/jlook/). [jNice](http://www.whitespace-creative.com/jquery/jNice/). [Ping Plugin](http://www.brainfault.com/2007/07/07/pin-plugin-reloaded/). [Toggle Form Text](http://grzegorz.frydrychowicz.net/jquery_toggleformtext/). [ToggleVal](http://thoughts.kuzemchak.net/entry/toggleval-for-jquery/). [jQuery Field Plugin](http://www.pengoworks.com/workshop/jquery/field.plugin.htm). [jQuery Form’n Field plugin](http://code.befruit.com/). [jQuery Checkbox manipulation](http://www.texotela.co.uk/code/jquery/checkboxes/). [jTagging](http://www.alcoholwang.cn/jquery/jTaggingDemo.htm). [jQuery labelcheck](http://code.google.com/p/labelcheck/). [Overlabel](http://scott.sauyet.com/thoughts/archives/2007/03/31/overlabel-with-jquery/). [3 state radio buttons](http://blog.amicoimmaginario.it/2007/08/28/jquery-plugin-3-state-radio-buttons/). [ShiftCheckbox jQuery Plugin](http://sanisoft-demo.com/jquery/plugins/shiftcheckbox/). [Watermark Input](http://digitalbush.com/projects/watermark-input-plugin). [jQuery Checkbox (checkboxes with imags)](http://kawika.org/jquery/checkbox/). [jQuery SpinButton Control](http://www.softwareunity.com/sandbox/jqueryspinbtn/). [jQuery Ajax Form Builder](http://www.phpletter.com/form_builder/demo.html). [jQuery Focus Fields](http://www.texotela.co.uk/code/jquery/focusfields/). [jQuery Time Entry](http://home.iprimus.com.au/kbwood/jquery/timeEntry.html). ### 时间、日期和颜色选取(Time, Date and Color Picker) [jQuery UI Datepicker](http://marcgrabanski.com/code/ui-datepicker/). [jQuery date picker plugin](http://kelvinluck.com/assets/jquery/datePicker/). [jQuery Time Picker](http://code.google.com/p/jquery-timepicker/). [Time Picker](http://www.texotela.co.uk/code/jquery/timepicker/). [ClickPick](http://www.oakcitygraphics.com/jquery/clockpick/ClockPick.cfm). [TimePicker](http://labs.perifer.se/timedatepicker/). [Farbtastic jQuery Color Picker Plugin](http://acko.net/dev/farbtastic). [Color Picker by intelliance.fr](http://www.intelliance.fr/jquery/color_picker/). ### 投票插件(Rating Plugins) [jQuery Star Rating Plugin](http://www.phpletter.com/Demo/Jquery-Star-Rating-Plugin/#). [jQuery Star Rater](http://www.m3nt0r.de/devel/raterDemo/). [Content rater with asp.net, ajax and jQuery](http://riderdesign.com/articles/displayarticle.aspx?articleid=21). [Half-Star Rating Plugin](http://www.learningjquery.com/2007/05/half-star-rating-plugin). ### 搜索插件(Search Plugins) [jQuery Suggest](http://www.vulgarisoip.com/2007/08/06/jquerysuggest-11/). [jQuery Autocomplete](http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/). [jQuery Autocomplete Mod](http://www.pengoworks.com/workshop/jquery/autocomplete.htm). [jQuery Autocomplete by AjaxDaddy](http://www.ajaxdaddy.com/demo-jquery-autocomplete.html). [jQuery Autocomplete Plugin with HTML formatting](http://dev.reach1to1.net/saurabh/jplugins/autocomplete/). [jQuery Autocompleter](http://interface.eyecon.ro/docs/autocomplete). [AutoCompleter (Tutorial with PHP&MySQL)](http://nodstrum.com/2007/09/19/autocompleter/). [quick Search jQuery Plugin](http://rikrikrik.com/jquery/quicksearch/). ### 编辑器(Inline Edit & Editors)[![JQuery_002](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d6555bd.gif)](http://images.cnblogs.com/cnblogs_com/Terrylee/WindowsLiveWriter/240jQuery_128F5/JQuery_002_2.gif) [jTagEditor](http://www.jaysalvat.com/jquery/jtageditor/). [WYMeditor](http://demo.wymeditor.org/demo.html). [jQuery jFrame](http://garage.pimentech.net/scripts_doc_jquery_jframe/). [Jeditable - edit in place plugin for jQuery](http://www.appelsiini.net/projects/jeditable). [jQuery editable](http://www.dyve.net/jquery/?editable). [jQuery Disable Text Select Plugin](http://www.jdempster.com/category/jquery/disableTextSelect/). [Edit in Place with Ajax using jQuery](http://15daysofjquery.com/edit-in-place-with-ajax-using-jquery-javascript-library/15/). [jQuery Plugin - Another In-Place Editor](http://davehauenstein.com/blog/archives/28). [TableEditor](http://dev.iceburg.net/jquery/tableEditor/demo.php). [tEditable - in place table editing for jQuery](http://joshhundley.com/teditable-in-place-editing-for-tables/). ### 多媒体、视频、Flash等(Audio, Video, Flash, SVG, etc) [jMedia - accessible multi-media embedding](http://www.contentwithstructure.com/extras/jmedia). [JBEdit - Ajax online Video Editor](http://sourceforge.net/projects/jbedit/). [jQuery MP3 Plugin](http://www.sean-o.com/jquery/jmp3/). [jQuery Media Plugin](http://malsup.com/jquery/media/). [jQuery Flash Plugin](http://jquery.lukelutman.com/plugins/flash/index.html). [Embed QuickTime](http://www.solitude.dk/archives/embedquicktime/). [SVG Integration](http://keith-wood.name/svg.html). ### 图片(Photos/Images/Galleries) [ThickBox](http://jquery.com/demo/thickbox/). [jQuery lightBox plugin](http://leandrovieira.com/projects/jquery/lightbox/). [jQuery Image Strip](http://blog.joshuaeichorn.com/archives/2007/01/11/jquery-image-strip/). [jQuery slideViewer](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html). [jQuery jqGalScroll 2.0](http://benjaminsterling.com/2007/09/09/jquery-jqgalscroll-photo-gallery/). [jQuery - jqGalViewII](http://benjaminsterling.com/2007/10/02/jquery-jqgalviewii-photo-gallery/). [jQuery - jqGalViewIII](http://benjaminsterling.com/2007/10/21/jqgalviewiii-proof-of-concept/). [jQuery Photo Slider](http://opiefoto.com/articles/photoslider). [jQuery Thumbs - easily create thumbnails](http://joanpiedra.com/jquery/thumbs/). [jQuery jQIR Image Replacement](http://www.texotela.co.uk/code/jquery/jQIR/). [jCarousel Lite](http://www.gmarwaha.com/jquery/jcarousellite/index.php#what). [jQPanView](http://projects.sevir.org/storage/jpanview/index.html). [jCarousel](http://sorgalla.com/projects/jcarousel/#Examples). [Interface Imagebox](http://www.intelliance.fr/jquery/imagebox/). [Image Gallery using jQuery, Interface & Reflactions](http://www.getintothis.com/blog/2006/10/12/image-gallery-using-jquery-interface-reflections/). [simple jQuery Gallery](http://realazy.org/lab/jquery/j-gallery/). [jQuery Gallery Module](http://chicagosocial.com/gallery/). [EO Gallery](http://www.eogallery.com/). [jQuery ScrollShow](http://flesler.blogspot.com/search/label/jQuery.ScrollShow). [jQuery Cycle Plugin](http://www.malsup.com/jquery/cycle/). [jQuery Flickr](http://www.projectatomic.com/en/flickr.htm). [jQuery Lazy Load Images Plugin](http://www.appelsiini.net/2007/9/lazy-load-images-jquery-plugin). [Zoomi - Zoomable Thumbnails](http://www.sunsean.com/zoomi/). [jQuery Crop - crop any image on the fly](http://remysharp.com/2007/03/19/a-few-more-jquery-plugins-crop-labelover-and-pluck/#crop). [Image Reflection](http://jquery.com/plugins/project/reflection). ### Google地图(Google Map) [jQuery Plugin googlemaps](http://www.dyve.net/jquery/?googlemaps). [jMaps jQuery Maps Framework](http://code.google.com/p/jmaps/). [jQmaps](http://projects.sevir.org/storage/jqmaps/index.html). [jQuery & Google Maps](http://olbertz.de/jquery/googlemap.html#). [jQuery Maps Interface forr Google and Yahoo maps](http://snippets.dzone.com/posts/show/4361). [jQuery J Maps - by Tane Piper](http://webrocket.ulmb.com/jmaps/). ### 游戏(Games) [Tetris with jQuery](http://fmarcia.info/jquery/tetris/tetris.html). [jQuery Chess](http://64squar.es/). [Mad Libs Word Game](http://www.bennadel.com/blog/623-jQuery-Demo-Mad-Libs-Word-Game.htm). [jQuery Puzzle](http://www.alexatnet.com/node/68). [jQuery Solar System (not a game but awesome jQuery Stuff)](http://www.willjessup.com/sandbox/jquery/solar_system/rotator.html). ### 表格等(Tables, Grids etc.) [UI/Tablesorter](http://docs.jquery.com/Plugins/Tablesorter).[![JQuery_003](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-23_56f252d663900.gif)](http://images.cnblogs.com/cnblogs_com/Terrylee/WindowsLiveWriter/240jQuery_128F5/JQuery_003_2.gif) [jQuery ingrid](http://www.reconstrukt.com/ingrid/). [jQuery Grid Plugin](http://www.trirand.com/blog/?p=13). [Table Filter - awesome!](http://ideamill.synaptrixgroup.com/jquery/tablefilter/tabletest.htm). [TableEditor](http://dev.iceburg.net/jquery/tableEditor/demo.php). [jQuery Tree Tables](http://www.hanpau.com/jquery/unobtrusivetreetable.php). [Expandable “Detail” Table Rows](http://www.javascripttoolbox.com/jquery/#expandablerows). [Sortable Table ColdFusion Costum Tag with jQuery UI](http://www.remotesynthesis.com/blog/index.cfm/2007/9/25/Sortable-Table-ColdFusion-Custom-Tag-with-jQueryUI). [jQuery Bubble](http://flesler.blogspot.com/2007/10/jquerybubble.html). [TableSorter](http://tablesorter.com/docs/). [Scrollable HTML Table](http://www.webtoolkit.info/demo/jquery/scrollable/demo.html). [jQuery column Manager Plugin](http://p.sohei.org/stuff/jquery/columnmanager/demo/demo.html). [jQuery tableHover Plugin](http://p.sohei.org/stuff/jquery/tablehover/demo/demo.html). [jQuery columnHover Plugin](http://p.sohei.org/stuff/jquery/columnhover/demo/demo.html). [jQuery Grid](http://makoomba.altervista.org/grid/). [TableSorter plugin for jQuery](http://motherrussia.polyester.se/jquery-plugins/tablesorter/). [tEditable - in place table editing for jQuery](http://joshhundley.com/teditable-in-place-editing-for-tables/). [jQuery charToTable Plugin](http://www.hovinne.com/dev/jquery/chartotable/). [jQuery Grid Column Sizing](http://www.ita.es/jquery/jquery.grid.columnSizing.htm). [jQuery Grid Row Sizing](http://www.ita.es/jquery/jquery.grid.rowSizing.htm). ### 统计图(Charts, Presentation etc.) [jQuery Wizard Plugin ](http://worcesterwideweb.com/2007/06/04/jquery-wizard-plugin/). [jQuery Chart Plugin](http://www.reach1to1.com/sandbox/jquery/jqchart/). [Bar Chart](http://ejohn.org/apps/speed/). ### 边框、圆角、背景(Border, Corners, Background) [jQuery Corner](http://www.malsup.com/jquery/corner/). [jQuery Curvy Corner](http://blue-anvil.com/archives/anti-aliased-rounded-corners-with-jquery). [Nifty jQuery Corner](http://dev.jquery.com/%7Epaul/plugins/nifty/example.html). [Transparent Corners](http://illandril.net/jQuery/transparentCorners/). [jQuery Corner Gallery](http://www.methvin.com/jquery/jq-corner.html). [Gradient Plugin](http://blog.brandonaaron.net/my-jquery-plugins/gradient/). ### 文字和超链接(Text and Links) [jQuery Spoiler plugin](http://wanderinghorse.net/computing/javascript/jquery/spoilers/demo.html). [Text Highlighting](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html). [Disable Text Select Plugin](http://www.jdempster.com/category/jquery/disableTextSelect/). [jQuery Newsticker](http://www.texotela.co.uk/code/jquery/newsticker/). [Auto line-height Plugin](http://www.ollicle.com/2007/jun/03/jquery_lineheight_flexible.html). [Textgrad - a text gradient plugin](http://agencenp.net/textgrad/textgrad.html). [LinkLook - a link thumbnail preview](http://kawika.org/jquery/linklook/). [pager jQuery Plugin](http://rikrikrik.com/jquery/pager/#examples). [shortKeys jQuery Plugin](http://rikrikrik.com/jquery/shortkeys/). [jQuery Biggerlink](http://www.ollicle.com/eg/jquery/biggerlink). [jQuery Ajax Link Checker](http://troy.dyle.net/linkchecker/). ### 鼠标提示(Tooltips) [jQuery Plugin - Tooltip](http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/). [jTip - The jQuery Tool Tip](http://www.codylindley.com/blogstuff/js/jtip/). [clueTip](http://examples.learningjquery.com/62/demo/index.html#examplesection). [BetterTip](http://edgarverle.com/BetterTip/default.cfm). [Flash Tooltips using jQuery](http://ioreader.com/2007/05/15/flash-tooltips-using-jquery/). [ToolTip](http://www.texotela.co.uk/code/jquery/tooltipdemo/). ### 菜单和导航(Menus, Navigations) [jQuery Tabs Plugin - awesome! ](http://stilbuero.de/jquery/tabs_3/). [[demo nested tabs](http://stilbuero.de/jquery/tabs_3/nested.html).] [another jQuery nested Tab Set example (based on jQuery Tabs Plugin)](http://blog.cutterscrossing.com/index.cfm/2007/6/15/Updated-JQuery-Nested-Tab-Set-with-Demo). [jQuery idTabs](http://www.sunsean.com/idTabs/). [jdMenu - Hierarchical Menu Plugin for jQuery](http://jdsharp.us/jQuery/plugins/jdMenu/). [jQuery SuckerFish Style](http://be.twixt.us/jquery/suckerFish.php). [jQuery Plugin Treeview](http://bassistance.de/jquery-plugins/jquery-plugin-treeview/). [treeView Basic](http://be.twixt.us/jquery/treeView.php). [FastFind Menu](http://labs.activespotlight.net/jQuery/menu_demo.html). [Sliding Menu](http://www.getintothis.com/blog/2006/09/26/my-first-jquery-plugin-a-sliding-menu/). [Lava Lamp jQuery Menu](http://gmarwaha.com/blog/?p=7). [jQuery iconDock](http://icon.cat/wiki/IconDock_En#iconDock_jQuery_Plugin). [jVariations Control Panel](http://cherne.net/brian/resources/jquery.variations.html). [ContextMenu plugin](http://www.trendskitchens.co.nz/jquery/contextmenu/). [clickMenu](http://p.sohei.org/jquery-plugins/clickmenu/). [CSS Dock Menu](http://www.ndesign-studio.com/blog/mac/css-dock-menu). [jQuery Pop-up Menu Tutorial](http://webexpose.org/2006/12/28/jquery-pop-up-menu-tutorial/). [Sliding Menu](http://www.getintothis.com/blog/2006/09/26/my-first-jquery-plugin-a-sliding-menu/). [http://stilbuero.de/jquery/tabs_3/](http://stilbuero.de/jquery/tabs_3/ "http://stilbuero.de/jquery/tabs_3/") ### 幻灯、翻转等(Accordions, Slide and Toggle stuff) [jQuery Plugin Accordion](http://bassistance.de/jquery-plugins/jquery-plugin-accordion/). [jQuery Accordion Plugin Horizontal Way](http://fmarcia.info/jquery/accordion.html). [haccordion - a simple horizontal accordion plugin for jQuery](http://letmehaveblog.blogspot.com/2007/10/haccordion-simple-horizontal-accordion.html). [Horizontal Accordion by portalzine.de](http://dev.portalzine.de/index?/Horizontal_Accordion--print). [HoverAccordion](http://berndmatzner.de/jquery/hoveraccordion/). [Accordion Example from fmarcia.info](http://fmarcia.info/jquery/accordion.html). [jQuery Accordion Example](http://blog.evaria.com/wp-content/themes/blogvaria/jquery/index.php). [jQuery Demo - Expandable Sidebar Menu](http://jquery.com/files/demo/dl-done.html). [Sliding Panels for jQuery](http://www.andreacfm.com/examples/jQpanels/). [jQuery ToggleElements](http://jquery.andreaseberhard.de/toggleElements/). [Coda Slider](http://www.ndoherty.com/demos/coda-slider/). [jCarousel](http://sorgalla.com/projects/jcarousel/#Examples). [Accesible News Slider Plugin](http://www.reindel.com/accessible_news_slider/). [Showing and Hiding code Examples](http://icant.co.uk/sandbox/jquerycodeview/). [jQuery Easing Plugin](http://gsgd.co.uk/sandbox/jquery/easing/). [jQuery Portlets](http://sonspring.com/journal/jquery-portlets). [AutoScroll](http://jdsharp.us/jQuery/plugins/AutoScroll/). [Innerfade](http://medienfreunde.com/lab/innerfade/). ### 拖放插件(Drag and Drop) [UI/Draggables](http://docs.jquery.com/UI/Draggables). [EasyDrag jQuery Plugin](http://fromvega.com/wordpress/2007/07/14/easydrag-jquery-plugin/). [jQuery Portlets](http://sonspring.com/journal/jquery-portlets). [jqDnR - drag, drop resize](http://dev.iceburg.net/jquery/jqDnR/). [Drag Demos](http://interface.eyecon.ro/demos/drag.html). ### XML XSL JSON Feeds [XSLT Plugin](http://www.jongma.org/webtools/jquery/xslt/). [jQuery Ajax call and result XML parsing](http://cgaskell.wordpress.com/2006/11/02/jquery-ajax-call-and-result-xml-parsing/). [xmlObjectifier - Converts XML DOM to JSON](http://jquery.com/plugins/project/xmlObjectifier). [jQuery XSL Transform](http://jquery.glyphix.com/). [jQuery Taconite - multiple Dom updates](http://malsup.com/jquery/taconite/). [RSS/ATOM Feed Parser Plugin](http://www.hovinne.com/blog/index.php/2007/07/15/132-jfeed-jquery-rss-atom-feed-parser-plugin). [jQuery Google Feed Plugin](http://www.malsup.com/jquery/gfeed/). ### 浏览器(Browserstuff) [Wresize - IE Resize event Fix Plugin](http://noteslog.com/post/how-to-fix-the-resize-event-in-ie/). [jQuery ifixpng](http://jquery.khurshid.com/ifixpng.php). [jQuery pngFix](http://jquery.andreaseberhard.de/pngFix/). [Link Scrubber - removes the dotted line onfocus from links](http://www.crismancich.de/jquery/plugins/linkscrubber/). [jQuery Perciformes - the entire suckerfish familly under one roof](http://www.matthewjrichards.co.uk/articles/2007/06/25/jquery-perciformes-the-entire-suckerfish-familly-under-one-roof). [Background Iframe](http://blog.brandonaaron.net/my-jquery-plugins/background-iframe/). [QinIE - for proper display of Q tags in IE](http://jquery.com/plugins/project/QinIE). [jQuery Accessibility Plugin](http://webrocket.ulmb.com/ability/). [jQuery MouseWheel Plugin](http://www.ogonek.net/mousewheel/jquery-demo.html). ### 对话框、确认窗口(Alert, Prompt, Confirm Windows) [jQuery Impromptu](http://trentrichardson.com/Impromptu/). [jQuery Confirm Plugin](http://nadiaspot.com/jquery/confirm). [jqModal](http://dev.iceburg.net/jquery/jqModal/). [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/). ### CSS [jQuery Style Switcher](http://www.kelvinluck.com/article/switch-stylesheets-with-jquery). [JSS - Javascript StyleSheets](http://andykent.bingodisk.com/bingo/public/jss/). [jQuery Rule - creation/manipulation of CSS Rules](http://flesler.blogspot.com/2007/11/jqueryrule.html). [jPrintArea](http://www.designerkamal.com/jPrintArea/). ### DOM、AJAX和其它JQuery插件(DOM, Ajax and other jQuery plugins) [FlyDOM](http://flydom.socianet.com/). [jQuery Dimenion Plugin](http://brandonaaron.net/docs/dimensions/#getting-started). [jQuery Loggin](http://happygiraffe.net/blog/articles/2007/09/26/jquery-logging). [Metadata - extract metadata from classes, attributes, elements](http://jquery.com/plugins/project/metadata). [Super-tiny Client-Side Include Javascript jQuery Plugin](http://johannburkard.de/blog/programming/javascript/inc-a-super-tiny-client-side-include-javascript-jquery-plugin.html). [Undo Made Easy with Ajax](http://humanized.com/weblog/2007/09/14/undo-made-easy-with-ajax-part-1/). [JHeartbeat - periodically poll the server](http://www.jasons-toolbox.com/JHeartbeat/). [Lazy Load Plugin](http://www.appelsiini.net/projects/lazyload). [Live Query](http://blog.brandonaaron.net/2007/08/19/new-plugin-live-query/). [jQuery Timers](http://jquery.offput.ca/every/). [jQuery Share it - display social bookmarking icons](http://www.joanpiedra.com/jquery/shareit/). [jQuery serverCookieJar](http://www.jdempster.com/category/code/jquery/cookiejar/). [jQuery autoSave](http://ideamill.synaptrixgroup.com/?p=3). [jQuery Puffer](http://www.semicomplete.com/blog/geekery/jquery-interface-puffer.html). [jQuery iFrame Plugin](http://33rockers.com/jquery/iframe-demo/). [Cookie Plugin for jQuery](http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/). [jQuery Spy - awesome plugin](http://leftlogic.com/lounge/articles/jquery_spy2). [Effect Delay Trick](http://www.learningjquery.com/2007/01/effect-delay-trick). [jQuick - a quick tag creator for jQuery](http://jquick.sullof.com/jquick/).[ Metaobjects](http://noteslog.com/post/metaobjects-11-released-today/). [elementReady](http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/).
';

jQuery 可编辑表格文本域,支持键盘快捷操作

最后更新于:2022-04-01 10:05:03

~~~ 可以和后台进行互动,通过第一列的值进行ajax请求。然后给后面的单元格进行赋值操作。支持键盘添加一行、删除一行表格、支持上下左右,快捷移到获得焦点操作。以及键盘事件对数字进行验证等。 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>table editor</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> .tableRow1 { background-color: #E6F3FC; } .tableRow2 { background-color: #ffffff; } .tableRow3 { background-color: #FFFFC9; color: #D40F16; } .tableHead { font-size: 12px; color: #FFFFFF; font-weight: bold; white-space: nowrap; word-break : keep-all ; background-color: #2897E6; } </style> <script type="text/javascript"> var htmlTemplate = '<tr align="center"><td><input type="text" name="report_num" size="20"/>'; htmlTemplate += '<input type="hidden" name="consign_id"/><br/>'; htmlTemplate += '<span name="msg" style="color: red;"></span></td>'; htmlTemplate += '<td><input type="text" name="contract_num" size="15"/></td>'; htmlTemplate += '<td><input type="text" name="wt_num" size="15"/></td>'; htmlTemplate += '<td><input type="text" name="wt_company" size="20"/></td>' htmlTemplate += '<td><input type="text" name="project_name" size="20"/></td>' htmlTemplate += '<td><input type="text" name="project_address" size="20"/></td>'; htmlTemplate += '<td><input type="hidden" name="item_id"/><input type="text" name="item_name" size="15"/></td>'; htmlTemplate += '<td><input type="text" name="report_count" size="3"/></td>'; htmlTemplate += '<td><input type="text" name="price" size="5"/></td>'; htmlTemplate += '<td><input type="text" name="amount" size="5"/></td>'; htmlTemplate += '<td><input type="text" name="ought_fare" size="5"/></td></tr>'; //添加一行表格记录 function addRowEl(textInput, currentEL) { //textInput = $(this),jQuery会自动传入触发当前事件的一个对象,即textInput,也就是这里的$(this) var el = currentEL == undefined ? $(this) : currentEL; if (el.attr("name") == "report_num") { getReportInfo(el); } else { var trEl = el.parent().parent(); if (isAdd(trEl)) { //var tabEl = $(this).parentsUntil("table"); //trEl.clone(true).appendTo(trEl.parent()); var template = $(htmlTemplate); template.appendTo(trEl.parent()); template.find(":text").focusin(onReportNum).focusout(onLoadReportInfo).keyup(onInputKeyUp); template.find(":text[name='report_num']").focus().focusin(); addClass(); } } } //失去焦点时,添加一条tr行记录 function onReportNum() { var el = $(this); var trEl = el.parent().parent(); if (el.attr("name") == "report_num") { if (el.val() == "") { var userName = "H"; if (userName.length > 0) { el.val(userName.substring(0, 1) + new Date().getYear()); } } if (isAdd(trEl)) { var template = $(htmlTemplate); template.appendTo(trEl.parent()); template.find(":text").focusin(onReportNum).focusout(onLoadReportInfo).keyup(onInputKeyUp); template.find(":text[name='report_num']").focusin(onReportNum).focus().focusin(); addClass(); } } else if (el.attr("name") == "ought_fare") { var price = trEl.find(":text[name='price']").val(); var count = trEl.find(":text[name='amount']").val(); if (price != "" && count != "") { el.val(parseFloat(price)*parseInt(count)); } } } //验证字段值是否为空,不为空则可以添加一行 function isAdd(trEl) { var allInput = trEl.parent().find(":text"); for (var i = 0; i < allInput.length; i++) { var temp = $(allInput[i]); var index = $.inArray(temp.attr("name"), ["report_num", "contract_num", "wt_num", "wt_company", "project_name", "item_name"]); if (index != -1) { if (temp.attr("name") == "report_num") { if (temp.val() == "E2010" || temp.val() == "") { return false; } } else { if(temp.val() == "") { return false; } } } } return true; } function flaotInputOnly() { if (event.keyCode > 57 || event.keyCode < 46 || event.keyCode == 47) event.keyCode = 0; } String.prototype.replaceAll = function(s1, s2) { return this.replace(new RegExp(s1, "gm"), s2); //g全局 } //获得当前光标的索引 function getFocusIndex(aryTr, currentEL) { var i = 0; var j = -1; $(aryTr).each(function () {//得到当前元素索引 if (currentEL.attr("name") == $(this).attr("name")) { j = i; } i++; }); return j; } function onInputKeyUp(e) { var event = e || window.event; var currKeyCode = event.keyCode || event.which || event.charCode; var currentEL = $(this); if (currentEL.attr("name") == "report_count" || currentEL.attr("name") == "amount") { currentEL.val(currentEL.val().replace(//D/g,''));//验证整数 } else if (currentEL.attr("name") == "price" || currentEL.attr("name") == "ought_fare") { var val = currentEL.val();//验证小数 if (parseFloat(val) != val) { var ar = val.split(''); for(var i = 0; i < ar.length; i++) { var charCode = ar[i].charCodeAt(0); if (charCode > 57 || charCode < 46 || charCode == 47) { currentEL.val(val.replaceAll(ar[i], '')); } } } } var currentTd = currentEL.parent(); var currentTr = currentTd.parent(); var aryTr = currentTr.find(":text").toArray(); var nextTd = currentTd.next("td"); var prevTd = currentTd.prev("td"); //alert(e.keyCode + ":" + currKeyCode); if (currKeyCode == 13) {//回车,enter键 nextTd.find(":text").focus().focusin();//获得下一文本域让其获得焦点 addRowEl(undefined, currentEL);//添加一行 } else if (currKeyCode == 45) { //insert键,添加一行 addRowEl(undefined, currentEL); } else if (currKeyCode == 46) { //delete键,删除一行 var tab = currentTr.parent(); var j = getFocusIndex(aryTr, currentEL); var prevTr = currentTr.prev("tr"); var prevInput = prevTr.find(":text:eq(" + j + ")"); if (prevInput.attr("name") != undefined) { prevInput.focus().focusin(); } if (tab.get(0).rows.length != 2) { currentTr.remove(); } } else if (currKeyCode == 39) { //right键,后一个、右 //如果是报告编号文本域就调用ajax方法并设置委托的信息 onLoadReportInfo(undefined, currentEL); nextTd.find(":text").focus().focusin(); } else if (currKeyCode == 38) {//up键,上 onLoadReportInfo(undefined, currentEL); //得到当前元素索引 var j = getFocusIndex(aryTr, currentEL); var prevTr = currentTr.prev("tr"); var prevInput = prevTr.find(":text:eq(" + j + ")"); if (prevInput.attr("name") != undefined) { prevInput.focus().focusin(); } } else if (currKeyCode == 40) {//down键,下一个 onLoadReportInfo(undefined, currentEL); var j = getFocusIndex(aryTr, currentEL); var nextTr = currentTr.next("tr"); var nextInput = nextTr.find(":text:eq(" + j + ")"); if (nextInput.attr("name") != undefined) { nextInput.focus().focusin(); } } else if (currKeyCode == 37) {//left键,左、前 onLoadReportInfo(undefined, currentEL); prevTd.find(":text").focus().focusin(); } } //根据报告编号加载委托信息 function onLoadReportInfo(textInput, currentEL) { var el = currentEL == undefined ? $(this) : currentEL; if (el.attr("name") == "report_num") { getReportInfo(el); } } //ajax请求,通过报告编号获得委托信息 function getReportInfo(el) { var reportNum = $(el); var trEl = reportNum.parent().parent(); var idEL = reportNum.next(":hidden[name='id']"); var reportVal = reportNum.val(); var aryNum = $("#sealTab :text[name='report_num']").toArray(); var aryResult = $.grep(aryNum, function (o) { return $(o).val() == reportVal; }); if (aryResult.length > 1) { reportNum.parent().find("span[name='msg']").text("该编号已申请,确定重复申请!"); reportNum.attr("flag", "exist"); //return; } if (reportVal != "") { $.post("transaction/reportSeal.do?method=getInfo", {id: idEL.val(), REPORT_NUM: reportVal}, function (data) { var rs = eval(data); if (rs.length > 0) { if (!rs[0].valid){ reportNum.parent().find("span[name='msg']").text("没有查询到该编号的信息!"); reportNum.attr("flag", "invalid"); return; } else { if (rs.length > 2) { $.each(rs[2], function (field, value) { if (value != "") { trEl.find("input[name='" + field + "']").val(value); } }); } } if (!rs[1].exists) { reportNum.parent().find("span[name='msg']").empty(); reportNum.attr("flag", "valid"); } else { reportNum.parent().find("span[name='msg']").text("该编号已申请,确定重复申请!"); reportNum.attr("flag", "exist"); } } }); } } $(function () { addClass(); //为sealTab中所有的文本域添加获得焦点、事情焦点事件 $("#sealTab :text").focusin(onReportNum).keyup(onInputKeyUp).focusout(onLoadReportInfo); }); function addClass() { $("#sealTr").nextAll().each(function (i) { return i % 2 == 0 ? $(this).addClass("tableRow1").removeClass("tableRow2") : $(this).addClass("tableRow2").removeClass("tableRow1"); }); } </script> </head> <body bgcolor="#ffffff"> <font color="red" style="font-size: 12px;">注意:*标记的列表格为必填的;insert插入一行(*号标记数据填写完整时)、delete键删除当前行(一行记录时不能删除)</font> <table id="sealTab" width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#C7CED4"> <tr id="sealTr" class="tableHead" valign="middle"> <td align="center"> <span style="color:#ffffff">报告编号</span> <font color="red">*</font> </td> <td align="center"> <span style="color:#ffffff">合同编号</span> </td> <td align="center"> <span style="color:#ffffff">委托编号</span> </td> <td align="center"> <span style="color:#ffffff">委托单位</span> </td> <td align="center"> <span style="color:#ffffff">工程名称</span> </td> <td align="center"> <span style="color:#ffffff">工程地点</span> </td> <td align="center"> <span style="color:#ffffff">检测项目</span> </td> <td align="center"> <span style="color:#ffffff">份数</span> </td> <td align="center"> <span style="color:#ffffff">单价</span> </td> <td align="center"> <span style="color:#ffffff">数量</span> </td> <td align="center"> <span style="color:#ffffff">总价</span> </td> </tr> <tr align="center"> <td> <input type="text" name="report_num" size="20"/> <input type="hidden" name="id"/> <input type="hidden" name="consign_id"/> <span name="msg" style="color: red;"></span> </td> <td> <input type="text" name="contract_num" size="15"/> </td> <td> <input type="text" name="wt_num" size="15"/> </td> <td> <input type="text" name="wt_company" size="20"/> </td> <td> <input type="text" name="project_name" size="20"/> </td> <td> <input type="text" name="project_address" size="20"/> </td> <td> <input type="hidden" name="item_id"/> <input type="text" name="item_name" size="15"/> </td> <td> <input type="text" name="report_count" size="3"/> </td> <td> <input type="text" name="price" size="5"/> </td> <td> <input type="text" name="amount" size="5"/> </td> <td> <input type="text" name="ought_fare" size="5"/> </td> </tr> </table> </body> </html> ~~~ ~~~ //ajax请求相关java code: public String getConsigJSON(String reportNum, String id) throws Exception { String sql = "select top 1 m.id as consign_id, contract_num,wt_num,wt_company,project_name,project_prov+project_city+project_area project_address,m.report_count,item_id,ought_fare,s.name item_name from MM_Consign m, SS_subject s where item_id = s.id and report_num = '" + reportNum + "'"; StringBuffer json = new StringBuffer("["); try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); RowSetDynaClass rsdc = new RowSetDynaClass(rs); List list = rsdc.getRows(); /*if ("".equals(id)) { String validValue = isValid(reportNum); json.append("{valid:").append(validValue).append("},"); String existsValue = this.isExists(reportNum); json.append("{exists:").append(existsValue).append("}"); } else {*/ String num = getReportNum(id); if (num.equals(reportNum)) { json.append("{valid:true},"); json.append("{exists:false}"); } else { String validValue = isValid(reportNum); json.append("{valid:").append(validValue).append("},"); String existsValue = this.isExists(reportNum); json.append("{exists:").append(existsValue).append("}"); } //} for (int j = 0, len = list.size(); j < len; j++) { json.append(",{"); DynaBean dyna = (DynaBean) list.get(j); for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i == rsmd.getColumnCount()) { json.append(rsmd.getColumnName(i)).append(":/"") .append(FunctionStatic.getNullString(BeanUtils.getSimpleProperty(dyna, rsmd.getColumnName(i).toLowerCase()))) .append("/""); } else { json.append(rsmd.getColumnName(i)).append(":/"") .append(FunctionStatic.getNullString(BeanUtils.getSimpleProperty(dyna, rsmd.getColumnName(i).toLowerCase()))) .append("/","); } } json.append("}"); /*if (j < len - 1) { json.append(","); }*/ } json.append("]"); } catch (Exception e) { e.printStackTrace(); throw e; } return json.toString(); } public String isValid(String reportNum) throws Exception { String bool = ""; try { prepar = conn.prepareStatement("select count(*) from MM_Consign where report_num = '" + reportNum + "'"); rs = prepar.executeQuery(); int count = rs.next() ? rs.getInt(1) : 0; bool = count > 0 ? "true" : "false"; } catch (Exception e) { e.printStackTrace(); throw e; } return bool; } public String isExists(String reportNum) throws Exception { String bool = ""; try { prepar = conn.prepareStatement("select count(*) from MM_ReportTransfer where report_num = '" + reportNum + "'"); rs = prepar.executeQuery(); int count = rs.next() ? rs.getInt(1) : 0; bool = count > 0 ? "true" : "false"; } catch (Exception e) { e.printStackTrace(); throw e; } return bool; } ~~~
';

jQuery 设置表格隔行变色、隔列变色

最后更新于:2022-04-01 10:05:01

~~~ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>隔行变色、隔列变色</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=gbk"> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(function () { $("table:eq(0) tr").each(function () { $(this).find("td").each(function (i) { if (i%2 != 0) { $(this).css("background-color","#CCCCFF"); } else { $(this).css("background-color","white"); } }); }); $("table:eq(1) tr").each(function (i) { if (i%2 != 0) { $(this).css("background-color","white"); } else { $(this).css("background-color","#CCCCFF"); } }); $("table:eq(2)").find("tr:even").css("background-color","white").end().find("tr:odd").css("background-color","#CCCCFF"); $("table:eq(3) tr").find("td:even").css("background-color","white").end().find("td:odd").css("background-color","#CCCCFF"); }); </script> </head> <body> <table width="80%"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> <hr /> <table width="80%"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> <hr /> <table width="80%"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> <hr /> <table width="80%"> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> <tr><td>1</td><td>2</td><td>3</td></tr> </table> </body> </html> ~~~
';

jQuery javaScript js 判断浏览器的类型、版本的方法

最后更新于:2022-04-01 10:04:59

~~~ 在jQuery判断浏览器的类型、版本都是通过正则完成的。 在1.4版本中: function brs ( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ //]([/w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ //]([/w.]+)/.exec( ua ) || /(msie) ([/w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([/w.]+))?/.exec( ua ) || []; /* webkit内核 遨游、Chrome、safari /(webkit)[ //]([/w.]+)/.exec( ua ) opera /(opera)(?:.*version)?[ //]([/w.]+)/.exec( ua ) ie /(msie) ([/w.]+)/.exec( ua ) firefox !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([/w.]+))?/.exec( ua ) */ return { browser: match[1] || "", version: match[2] || "0" }; } function test() { alert(brs(navigator.userAgent).browser + "-" + brs(navigator.userAgent).version); } 而在1.4之前略有不同: var userAgent = navigator.userAgent.toLowerCase(); var browser = { version: (userAgent.match( /.+(?:rv|it|ra|ie)[//: ]([/d.]+)/ ) || [])[1],//判断版本 safari: /webkit/.test( userAgent ), opera: /opera/.test( userAgent ), msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ) }; alert(browser.version + ":" + browser.msie); ~~~
';

jQuery 变动图片、滤镜效果

最后更新于:2022-04-01 10:04:56

~~~ 用jQuery写的简单的图片变化且带alpha滤镜的动态效果 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Alpha.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <mce:script type="text/javascript" src="extjs/adapter/jquery/jquery.js" mce_src="extjs/adapter/jquery/jquery.js"></mce:script> <mce:script type="text/javascript"> <!-- var ary = ["red", "blue", "#CCFFFF", "#99FFCC"]; var imgAry = new Array(); imgAry.push("http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/ed9e7094af4f2677d1135e93.jpg"); imgAry.push("http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/cf4013658b43f3ccf7365493.jpg"); imgAry.push("http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/2f78156fb7c8dae681cb4a93.jpg"); imgAry.push("http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/ed9e7094af1f2677d0135e23.jpg"); var i = 0; $(function () { $("div").css("width", "300px").css("height", "200px").css("border", "1px solid red"); $("img").css("width", "200px").css("height", "200px") .css("filter", "progid:DXImageTransform.Microsoft.Alpha(startX=0, startY=0, finishX=100, finishY=100,style=3,opacity=0,finishOpacity=100)"); /* 调节style=3,opacity=0,finishOpacity=100这三个值改变效果, style 渐变样式 0,1,2,3 opacity开始透明度 0 25 50 75 100 finishOpacity结束透明读0 25 50 75 100 */ show(); }); function show () { $("div").css("background-color", ary[i]); $("img").attr("src", imgAry[i]); i++; if (i > ary.length - 1) { i = 0; } setTimeout("show()", "1000"); } // --> </mce:script> </head> <body> <div> <img src="http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/cf4013658b43f3ccf7365493.jpg" mce_src="http://hiphotos.baidu.com/%BA%EC%C2%A5%C7%E9%C3%CE/pic/item/cf4013658b43f3ccf7365493.jpg"/> </div> </body> </html> ~~~
';

前言

最后更新于:2022-04-01 10:04:54

> 原文出处:[Ajax 专栏](http://blog.csdn.net/column/details/ajax.html) 作者:[ibm_hoojo](http://blog.csdn.net/ibm_hoojo) **本系列文章经作者授权在看云整理发布,未经作者允许,请勿转载!** # Ajax 专栏 > 介绍Ajax(xmlHttpRequest、jQuery、ExtJS、GXT、DWR、Mootools)相关技术知识
';