jQuery实用技巧必备(中)

2020-05-29 07:19:11易采站长站整理


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

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


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

19.简单的手风琴效果
这是一个实现手风琴效果快速简单的方法:
// 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;
});

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


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

这段代码会循环一组元素,并设置它们的高度为元素中的最大高。
21. 验证元素是否为空
This will allow you to check if an element is empty.


$(document).ready(function() {
if ($('#id').html()) {
// do something
}
});

22. 替换元素
Want to replace a div, or something else?


$(document).ready(function() {
$('#id').replaceWith('
<DIV>I have been replaced</DIV>

');
});