2025年3月15日 星期六 甲辰(龙)年 月十四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

分享 10 个很有用的 jQuery 代码片段

时间:12-14来源:作者:点击数:29
城东书院 www.cdsy.xyz

可重复使用 jQuery 代码片段,多年来 jQuery 成为了每个 Web 开发人员最喜欢使用库。 它使用简单、速度快并且功能非常强大。 在这篇文章中,我为大家分享一系列得心应手的 jQuery 代码片段,你可以保存并复制你到你的收藏中,这些片段是超级容易适应,以符合您自己的脚本。

平滑滚动到页面顶部

让我们通过一个非常受欢迎的和有用的片段开始这个名单:这4行代码将让你的访问者只需点击A链接即可平滑滚动到页面顶部(与平滑双击自动滚屏发布到页面顶部 #top 位于页面底部的id)。

  • $("a[href='#top']").click(function() {
  • $("html, body").animate({ scrollTop: 0 }, "slow");
  • return false;
  • });

复制表格的 thead 表

为了更好的阅读网页的内容,一般编写table表格的时候,会设置一个表头和表尾,内容都是一样的,那么就可以使用jquery的复制这段代码,精简代码。

  • var $tfoot = $('<tfoot></tfoot>');
  • $($('thead').clone(true, true).children().get().reverse()).each(function(){
  • $tfoot.append($(this));
  • });
  • $tfoot.insertAfter('table thead');

加载外部内容

你需要一些外部内容添加到div ? 这是很容易做到的jQuery的,如下面的例子:

  • $("#content").load("somefile.html", function(response, status, xhr) {
  • // error handling
  • if(status == "error") {
  • $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  • }
  • });

等高列

当你使用的列显示在您的网站内容,它肯定更好看,如果列有同等的高度。 下面的代码将采取所有div元素中.col类,并会根据大元调整自己的高度。 超好用!

  • var maxheight = 0;
  • $("div.col").each(function(){
  • if($(this).height() > maxheight) { maxheight = $(this).height(); }
  • });
  • $("div.col").height(maxheight);

表格隔行换色(斑马纹)

当在表上显示的数据,每一行交替颜色肯定会增加可读性。 这里有一个片段,自动CSS类添加到了两个一排。

  • $(document).ready(function(){
  • $("table tr:even").addClass('stripe');
  • });

部分页面刷新

如果你需要刷新页面只有一部分,下面3行代码有一定帮助。 在这个例子中,一个#refresh的div自动刷新每10秒。

  • setInterval(function() {
  • $("#refresh").load(location.href+" #refresh>*","");
  • }, 10000); // milliseconds to wait

预先载入图像

jQuery 的可以很容易地预装影像为背景,让游客将不必永远等待,当他们想显示图像。 这段代码就可以使用了,只是更新第 8 行的图像列表。

  • $.preloadImages = function() {
  • for(var i = 0; i<arguments.length; i++) {
  • $("<img />").attr("src", arguments[i]);
  • }
  • }
  • $(document).ready(function() {
  • $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
  • });

在新标签/窗口中打开外部链接

该 target="blank" 属性允许你强制开新窗口的链接。 虽然它是相关的,打开一个新标签或窗口的外部链接,同一个域的链接绝对应该在同一个窗口中打开。 此代码检测,如果一个链接是外部的,如果是,增加了一个 target="blank" 属性就可以了。

  • $('a').each(function() {
  • var a = new RegExp('/' + window.location.host + '/');
  • if(!a.test(this.href)) {
  • $(this).click(function(event) {
  • event.preventDefault();
  • event.stopPropagation();
  • window.open(this.href, '_blank');
  • });
  • }
  • });

设置窗口的全宽/高

这个方便的一段代码允许您创建根据视口全宽/高格。 该代码也处理窗口大小调整。 伟大的模态对话框或弹出窗口。

  • // global vars
  • var winWidth = $(window).width();
  • var winHeight = $(window).height();
  • // set initial div height / width
  • $('div').css({
  • 'width': winWidth,
  • 'height': winHeight,
  • });
  • // make sure div stays full width/height on resize
  • $(window).resize(function(){
  • $('div').css({
  • 'width': winWidth,
  • 'height': winHeight,
  • });
  • });

测试密码强度

当你让用户定义自己的密码,它通常是一件好事,表明有多强密码。 这正是这段代码做。 首先,假设此HTML:

  • <input type="password" name="pass" id="pass" />
  • <span id="passstrength"></span>

这里是相应的jQuery代码。 所输入的密码将使用正则表达式进行评估和消息将被返回给用户,让他知道,如果他所选择的密码为强,中,弱,或太短。

  • $('#pass').keyup(function(e) {
  • var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
  • var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
  • var enoughRegex = new RegExp("(?=.{6,}).*", "g");
  • if (false == enoughRegex.test($(this).val())) {
  • $('#passstrength').html('More Characters');
  • } else if (strongRegex.test($(this).val())) {
  • $('#passstrength').className = 'ok';
  • $('#passstrength').html('Strong!');
  • } else if (mediumRegex.test($(this).val())) {
  • $('#passstrength').className = 'alert';
  • $('#passstrength').html('Medium!');
  • } else {
  • $('#passstrength').className = 'error';
  • $('#passstrength').html('Weak!');
  • }
  • return true;
  • });

使用 jQuery 调整图像大小

虽然你应该(使用 PHP 和 GD 为例)调整在服务器端的图像也可以是有用的,以便能够使用jQuery来调整图像。 这里有一个片段来做到这一点。

  • $(window).bind("load", function() {
  • // IMAGE RESIZE
  • $('#product_cat_list img').each(function() {
  • var maxWidth = 120;
  • var maxHeight = 120;
  • var ratio = 0;
  • var width = $(this).width();
  • var height = $(this).height();
  • if(width > maxWidth){
  • ratio = maxWidth / width;
  • $(this).css("width", maxWidth);
  • $(this).css("height", height * ratio);
  • height = height * ratio;
  • }
  • var width = $(this).width();
  • var height = $(this).height();
  • if(height > maxHeight){
  • ratio = maxHeight / height;
  • $(this).css("height", maxHeight);
  • $(this).css("width", width * ratio);
  • width = width * ratio;
  • }
  • });
  • //$("#contentpage img").show();
  • // IMAGE RESIZE
  • });

滚动自动加载内容

一些网站如 Twitter 的滚动加载内容。 这意味着,所有内容都在一个页面上,只要你向下滚动动态加载。 这里是你如何能复制在您的网站这样的效果:

  • var loading = false;
  • $(window).scroll(function(){
  • if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
  • if(loading == false){
  • loading = true;
  • $('#loadingbar').css("display","block");
  • $.get("load.php?start="+$('#loaded_max').val(), function(loaded){
  • $('body').append(loaded);
  • $('#loaded_max').val(parseInt($('#loaded_max').val())+50);
  • $('#loadingbar').css("display","none");
  • loading = false;
  • });
  • }
  • }
  • });
  • $(document).ready(function() {
  • $('#loaded_max').val(50);
  • });

检查图像加载

这里有一个片段,我经常使用带有图像时,因为它是要知道如果一个图像加载或不是最好的方式。

  • var imgsrc = 'img/image1.png';
  • $('<img/>').load(function () {
  • alert('image loaded');
  • }).error(function () {
  • alert('error loading image');
  • }).attr('src', imgsrc);

列表按字母排序

在某些情况下,它可以是非常有用的一个排序一长串的英文字母顺序排列。 这段代码采取任何名单,并责成其元素按字母顺序。

  • $(function() {
  • $.fn.sortList = function() {
  • var mylist = $(this);
  • var listitems = $('li', mylist).get();
  • listitems.sort(function(a, b) {
  • var compA = $(a).text().toUpperCase();
  • var compB = $(b).text().toUpperCase();
  • return (compA < compB) ? -1 : 1;
  • });
  • $.each(listitems, function(i, itm) {
  • mylist.append(itm);
  • });
  • }
  • $("ul#demoOne").sortList();
  • });
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐