search
HomeWeb Front-endJS Tutorial15个jQuery小技巧分享

15个jQuery小技巧分享

Mar 13, 2018 pm 02:19 PM
jqueryshare

本文主要和大家分享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
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software