$(document).ready(function() { $('a[href*=#]').click(function() { if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { var $target = $(this.hash) $target = ($target.length && $target) || $('[name=' + this.hash.slice(1) + ']') if ($target.length) { var targetOffset = $target.offset().top $('html,body').animate({ scrollTop: targetOffset }, 900) returnfalse } } }) // how to use // place this where you want to scroll to<A name=top></A>// the link<A href="#top">go to top</A> })
获得鼠标指针XY值
Want to know where your mouse cursor is?
1 2 3 4 5 6
$(document).ready(function() { $().mousemove(function(e) { //display the x and y axis values inside the div with the id XY $('#XY').html('X Axis : ' + e.pageX + ' | Y Axis ' + e.pageY) }) // how to use<DIV id=XY></DIV> })
返回顶部按钮
你可以利用 animate 和 scrollTop 来实现返回顶部的动画,而不需要使用其他插件。
1 2 3 4 5
// Back to top $('a.top').click(function () { $(document.body).animate({scrollTop: 0}, 800); returnfalse;}); <!-- Create an anchor tag --><aclass="top"href="#">Back to top</a>
// 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') returnfalse })
让两个 DIV 高度相同
有时你需要让两个 div 高度相同,而不管它们里面的内容多少。可以使用下面的代码片段:
1 2 3 4 5 6 7 8
var $columns = $('.column') var height = 0 $columns.each(function() { if ($(this).height() > height) { height = $(this).height() } }) $columns.height(height)
这段代码会循环一组元素,并设置它们的高度为元素中的最大高。
验证元素是否为空
This will allow you to check if an element is empty.
1 2 3 4 5
$(document).ready(function() { if ($('#id').html()) { // do something } })
替换元素
1 2 3
$(document).ready(function() { $('#id').replaceWith('<DIV>I have been replaced</DIV>') })
jQuery 延时加载功能
1 2 3 4 5
$(document).ready(function() { window.setTimeout(function() { // do something }, 1000) })
移除单词功能
1 2 3 4
$(document).ready(function() { var el = $('#id') el.html(el.html().replace(/word/gi, '')) })
验证元素是否存在于 jquery 对象集合中
1 2 3 4 5
$(document).ready(function() { if ($('#id').length) { // do something } })
使整个 DIV 可点击
1 2 3 4 5 6 7 8 9
$(document).ready(function() { $('div').click(function() { //get the url from href attribute and launch the url window.location = $(this) .find('a') .attr('href') returnfalse }) // how to use<DIV><A href="index.html">home</A></DIV> })
$(document).ready(function() { $.extend($.expr[':'], { moreThen1000px: function(a) { return $(a).width() > 1000 } }) $('.box:moreThen1000px').click(function() { // 创建一个简单的js弹窗 alert('The element that you have clicked is over 1000 pixels wide') }) })
统计元素个数
1 2 3
$(document).ready(function() { $('p').size() })
使用自己的 Bullets
使用自己的 bullets 而不是标准 bullets?
1 2 3 4 5 6
$(document).ready(function() { $("ul").addClass("Replaced"); $("ul > li").prepend("‒ "); // how to use ul.Replaced { list-style : none; } });