Home Web Front-end JS Tutorial 15个jQuery小技巧分享

15个jQuery小技巧分享

Mar 13, 2018 pm 02:19 PM
jquery share

本文主要和大家分享15 个jQuery小技巧(干货)相关教程,具体实例代码请看下文,希望能帮助到大家。

1.返回顶部按钮

你可以利用animatescrollTop来实现返回顶部的动画,而不需要使用其他插件。

?

code

1

2

3

$('a.top').click(function(){

    $(document.body).animate({scrollTop:0},800);returnfalse

});

改变scrollTop的值可以调整返回距离顶部的距离,而animate的第二个参数是执行返回动作需要的时间(单位:毫秒)。

2.预加载图片

如果你的页面中使用了很多不可见的图片(如:hover 显示),你可能需要预加载它们:

?

code

1

2

3

$.preloadImages =function(){for(var i =0; i < arguments.length; i++){

$(&#39;<img>').attr('src', arguments[i]);}};

$.preloadImages('img/hover1.png','img/hover2.png');

3.检查图片是否加载完成

有时候你需要确保图片完成加载完成以便执行后面的操作:

?

code

1

2

3

$('img').load(function(){

  console.log('image load successful');

});

你可以把img替换为其他的ID或者class来检查指定图片是否加载完成。

4.自动修改破损图像

如果你碰巧在你的网站上发现了破碎的图像链接,你可以用一个不易被替换的图像来代替它们。添加这个简单的代码可以节省很多麻烦:

?

code

1

2

3

$('img').on('error',function(){

  $(this).prop('src','img/broken.png');

});

即使你的网站没有破碎的图像链接,添加这段代码也没有任何害处。

5.鼠标悬停(hover)切换Class属性

假如当用户鼠标悬停在一个可点击的元素上时,你希望改变其效果,下面这段代码可以在其悬停在元素上时添加class属性,当用户鼠标离开时,则自动取消该class属性:

?

code

1

2

3

4

$('.btn').hover(function(){

  $(this).addClass('hover');},function(){

    $(this).removeClass('hover');

});

你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用toggleClass方法:

?

code

1

2

3

$('.btn').hover(function(){

  $(this).toggleClass('hover');

});

注:直接使用CSS实现该效果可能是更好的解决方案,但你仍然有必要知道该方法。

6.禁用 input 字段

有时你可能需要禁用表单的submit按钮或者某个input字段,直到用户执行了某些操作(例如,检查“已阅读条款”复选框)。可以添加disabled属性,直到你想启用它时:

?

code

1

$('input[type="submit"]').prop('disabled',true);

你要做的就是执行removeAttr方法,并把要移除的属性作为参数传入:

?

code

1

$('input[type="submit"]').removeAttr('disabled');

7.阻止链接加载

有时你不希望链接到某个页面或者重新加载它,你可能希望它来做一些其他事情或者触发一些其他脚本,你可以这么做:

?

code

1

2

3

$('a.no-link').click(function(e){

  e.preventDefault();

});

8.切换 fade/slide

fade 和 slide 是我们在 jQuery 中经常使用的动画效果,它们可以使元素显示效果更好。但是如果你希望元素显示时使用第一种效果,而消失时使用第二种效果,则可以这么做:

?

code

1

2

3

4

5

6

$('.btn').click(function(){

  $('.element').fadeToggle('slow');

});

$('.btn').click(function(){

  $('.element').slideToggle('slow');

});

9.简单的手风琴效果

这是一个实现手风琴效果快速简单的方法:

?

code

1

2

3

4

$('#accordion').find('.content').hide();

$('#accordion').find('.accordion-header').click(function(){varnext= $(this).next();next.slideToggle('fast');

  $('.content').not(next).slideUp('fast');returnfalse;

});

10.让两个 p 高度相同

有时你需要让两个 p 高度相同,而不管它们里面的内容多少。可以使用下面的代码片段:

?

code

1

2

3

4

5

var $columns = $('.column');

var height =0;$columns.each(function(){if($(this).height()> height){

    height = $(this).height();}

});

$columns.height(height);

这段代码会循环一组元素,并设置它们的高度为元素中的最大高。

11.css3实现p的淡入淡出效果。

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

@-webkit-keyframes fadeIn{

0%{

opacity: 0;/*初始状态*/

flter:"Alpha(Opacity=0)";

}

20%{

opacity: 0.2;

flter:"Alpha(Opacity=0.2)";

}

40%{

opacity: 0.4;

flter:"Alpha(Opacity=0.4)";

}

60%{

opacity: 0.6;

flter:"Alpha(Opacity=0.6)";

}

80%{

opacity: 0.8;

flter:"Alpha(Opacity=0.8)";

}

100%{

opacity: 1.0;

flter:"Alpha(Opacity=1.0)";

}

}

.fadeInShow{

-webkit-animation-name: fadeIn;/*动画名称*/

-webkit-animation-duration: 300ms; /*动画持续时间*/

-webkit-animation-iteration-count: 1; /*动画次数*/

-webkit-animation-delay: 0s; /*延迟时间*/

}

引入动画效果:

?

code

1

2

3

4

5

$('.my-project-selector').hover(function(){

$('#project-popover').css('display','block').addClass('fadeInShow');

},function(){

$('#project-popover').css('display','none').removeClass('fadeInShow');

});

12、Jquery遍历一组checkbox复选框,取出选中的值放在数组里

?

code

1

2

3

4

5

6

var obj = $("input[name='projectId']"),arr=[],i=0;

for(;i<obj.length;i++){

  if(obj[i].checked){

    arr.push(obj[i].value);

  }

}

13、jquery的ajax错误error方法查看状态值代码

?

code

1

2

3

4

5

6

error: function(XMLHttpRequest) {

//(canceled)==捕捉到的状态值是 “0”

if(XMLHttpRequest.status=="0"){

//屏蔽canceled状态值

}

}

14、超出部分截取字符,显示“...”(超出的文字自动+省略号)

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$.fn.limit=function(){

var self = $("*[limit]");

self.each(

function(){

var objString = $.trim($(this).text());

var objLength = $.trim($(this).text()).length;

var num = $(this).attr("limit");

if(objLength > num){

$(this).attr("title",objString);

               objString = $(this).text(objString.substring(0,num) + "...");

            }

         }

   )

};

?

code

1

使用方式:<span limit="5">天空飘来五个字,那都不是事儿</span>

?

code

1

当前页面写入:

?

code

1

$("span[limit]").limit();

15、光标定位到字符最后(使用场景:input=text文本框获取焦点后,光标显示在字符最后)

?

code

1

//光标定位到字符最后

?

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$.fn.selectRange = function(start, end) {

returnthis.each(function() {

if(this.setSelectionRange) {

this.focus();

this.setSelectionRange(start, end);

      }elseif (this.createTextRange) {

var range = this.createTextRange();

         range.collapse(true);

         range.moveEnd('character', end);

         range.moveStart('character', start);

         range.select();

      }

   });

};

16、JS判断是否为数组:

?

code

1

Object.prototype.toString.call([1,2,3]) === [object Array]   //true

相关推荐:

10个必须把握的jquery小技巧

几个比较经典常用的jQuery小技巧_jquery

开发中可能会用到的jQuery小技巧_jquery

The above is the detailed content of 15个jQuery小技巧分享. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to share Quark Netdisk to Baidu Netdisk? How to share Quark Netdisk to Baidu Netdisk? Mar 14, 2024 pm 04:40 PM

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments How to share NetEase Cloud Music to WeChat Moments_Tutorial on sharing NetEase Cloud Music to WeChat Moments Mar 25, 2024 am 11:41 AM

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the &quot;Share to&quot; option at the bottom, and then select the first &quot;WeChat Moments&quot; allows you to share content to WeChat Moments.

How to share files with friends on Baidu Netdisk How to share files with friends on Baidu Netdisk Mar 25, 2024 pm 06:52 PM

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the &quot;Shared Members&quot; column 】, and finally check all

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Share two installation methods for HP printer drivers Share two installation methods for HP printer drivers Mar 13, 2024 pm 05:16 PM

HP printers are essential printing equipment in many offices. Installing the printer driver on the computer can perfectly solve problems such as the printer being unable to connect. So how to install HP printer driver? The editor below will introduce you to two HP printer driver installation methods. The first method: download the driver from the official website 1. Search the HP China official website in the search engine, and in the support column, select [Software and Drivers]. 2. Select the [Printer] category, enter your printer model in the search box, and click [Submit] to find your printer driver. 3. Select the corresponding printer according to your computer system. For win10, select the driver for win10 system. 4. After downloading successfully, find it in the folder

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Solve the problem that Discuz WeChat sharing cannot be displayed Solve the problem that Discuz WeChat sharing cannot be displayed Mar 09, 2024 pm 03:39 PM

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

See all articles