Home >Web Front-end >JS Tutorial >Pay attention to jquery skills and improve jquery skills (must learn for front-end development)_jquery

Pay attention to jquery skills and improve jquery skills (must learn for front-end development)_jquery

WBOY
WBOYOriginal
2016-05-16 15:34:001459browse

A collection of simple tips to help you improve your jQuery skills.

A small project started by Matt Smith, there are currently 14 tips. Bole Online will continue to follow up with updates.

Back to top button
Preload images
Check if the image is loaded
Automatically repair damaged pictures
Class switch on Hover
Disable input fields
Stop link loading
Fade/slide switch
Simple folding effect
Set two Divs to the same height
Open external link in new window
Find the text element
Switch between visible and hidden triggers

Back to top button

By using the animate and scrollTop methods in jQuery, you can create a simple back to top animation without the need for a plugin:

JavaScript

// Back to top
$('a.top').click(function (e) {
 e.preventDefault();
 $(document.body).animate({scrollTop: 0}, 800);
});

JavaScript

<!-- Create an anchor tag -->
<a class="top" href="#">Back to top</a>

Change the value of scrollTop to where you want the scrollbar to stop. And then what you do is, set it to go back to the top in 800 milliseconds.

Preload images

If your page uses a lot of images that are not initially visible (e.g. bound to hover), it is useful to preload them:

JavaScript

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $('<img>').attr('src', arguments[i]);
 }
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');

Check whether the image is loaded

Sometimes you may need to check whether the image is completely loaded before you can perform subsequent operations in the script:

JavaScript

$('img').load(function () {
 console.log('image load successful');
});

You can also check whether a specific image has been loaded by replacing the img tag with an ID or class.

Automatically repair damaged pictures

If you find that the image links on your website are broken, it will be troublesome to replace them one by one. This simple code can help a lot:

JavaScript

$('img').on('error', function () {
 $(this).prop('src', 'img/broken.png');
});

Even if you don’t have any broken links, adding this code will have no impact.

Class switching on Hover

If the user's mouse hovers over a clickable element on the page, you want to change the visual representation of this element. You can use the following code to add a class to the element when the user hovers it; remove the class when the user leaves the mouse:

JavaScript

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

You only need to add the necessary CSS. If you need a simpler way, you can also use the toggleClass method:

JavaScript

$('.btn').hover(function () {
 $(this).toggleClass('hover');
});


Note: CSS may be a faster solution for this example, but it’s still worth knowing.

Disable input field

Sometimes you may want to make a form's submit button or its text input box unavailable until the user performs a specific action (such as confirming the "I have read the terms" checkbox). Add disabled attribute to your input to achieve the effect you want:

JavaScript

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

When you want to change the value of disabled to false, just run the prop method on the input again.

JavaScript

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

Stop link loading

Sometimes you don’t want a link to jump to a page or reload the page, but want to be able to do something else, such as trigger other scripts. The following code is a little trick to disable the default behavior:

JavaScript

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

Fade/slide switch

Fade in and out and slide are animation effects that we often use jQuery to create. Maybe you just want to reveal an element when the user clicks on something, using fadeIn and slideDown are both great. But if you want the element to appear on the first click and disappear on the second click, the following code can do the job well:

JavaScript

// Fade
$('.btn').click(function () {
 $('.element').fadeToggle('slow');
});
// Toggle
$('.btn').click(function () {
 $('.element').slideToggle('slow');
});

Simple accordion effect

Here’s a quick and easy way to achieve an accordion effect:

JavaScript

// Close all panels
$('#accordion').find('.content').hide();
 
// Accordion
$('#accordion').find('.accordion-header').click(function () {
 var next = $(this).next();
 next.slideToggle('fast');
 $('.content').not(next).slideUp('fast');
 return false;
});

After adding this script, all you need to do is see if the script works properly within the necessary HTML.

Make the two Divs the same height

Sometimes you might want two divs to have the same height, regardless of what content they contain:

JavaScript

$('.div').css('min-height', $('.main-div').height());

This example sets min-height, meaning it can be larger than the main div, but never smaller. But a more flexible method is to iterate through the settings of a set of elements and set the height to the highest value in the element:

JavaScript

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

If you want all columns to be the same height:

JavaScript

var $rows = $('.same-height-columns');
$rows.each(function () {
 $(this).find('.column').height($(this).height());
});

在新标签/窗口打开站外链接
在一个新标签或者新窗口中打开外置链接,并确保站内链接会在相同的标签或窗口中打开:

JavaScript

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

注意:window.location.origin 在 IE 10 中不可用,该 issue 的修复方法。

通过文本找到元素

通过使用 jQuery 中的 contains() 选择器,你可以找到某个元素中的文本。如果文本不存在,该元素将会隐藏:

JavaScript

var search = $('#search').val();

$('div:not(:contains("' + search + '"))').hide();

视觉改变触发
当用户焦点在另外一个标签上,或重新回到标签时,触发 JavaScript:

JavaScript

$(document).on('visibilitychange', function (e) {
 if (e.target.visibilityState === "visible") {
  console.log('Tab is now in view!');
 } else if (e.target.visibilityState === "hidden") {
  console.log('Tab is now hidden!');
 }
});

Ajax 调用的错误处理

当某次 Ajax 调用返回 404 或 500 错误,就会执行错误处理。但如果没有定义该处理,其他 jQuery 代码或许会停止工作。可以通过下面这段代码定义一个全局 Ajax 错误处理:

JavaScript

$(document).ajaxError(function (e, xhr, settings, error) {
 console.log(error);
});

全能程序员交流QQ群290551701,群内程序员都是来自,百度、阿里、京东、小米、去哪儿、饿了吗、蓝港等高级程序员 ,拥有丰富的经验。加入我们,直线沟通技术大牛,最佳的学习环境,了解业内的一手的资讯。如果你想结实大牛,那 就加入进来,让大牛带你超神!

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