分享一些jquery常用代码片段

作者:Liaodeity - 2016年04月18日

点击text的input后,直接选中其中的所有文字

jquery 使用select();

$("input:text").click(function(){
    $(this).select();
});

平稳滑动到页面顶部

这是一个最广泛使用的jQuery效果:对一个链接点击下会平稳地将页面移动到顶部。这里没什么新的内容,但是每个开发者必须要会偶尔编写一下类似函数

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;});

固定在顶部

非常有用的代码片段,它允许一个元素固定在顶部。对导航按钮、工具栏或重要信息框是超级有用的。

$(function(){
    var $win = $(window)
    var $nav = $('.mytoolbar');
    var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;
    var isFixed=0;

    processScroll()
    $win.on('scroll', processScroll)

    function processScroll() {
    var i, scrollTop = $win.scrollTop()

    if (scrollTop >= navTop && !isFixed) { 
        isFixed = 1
        $nav.addClass('subnav-fixed')
    } else if (scrollTop <= navTop && isFixed) {
        isFixed = 0
         $nav.removeClass('subnav-fixed')
    }}

检测视窗宽度

现在移动设备比过时的电脑更普遍,能够方便去检测一个更小的视窗宽度会很有帮助。幸运的是,用jQuery来做超级简单。

var responsive_viewport = $(window).width();/* if is below 481px */
if (responsive_viewport < 481) {
    alert('Viewport is smaller than 481px.');} /* end smallest screen */

自动定位并修复损坏图片

如果你的站点比较大而且已经在线运行了好多年,你或多或少会遇到界面上某个地方有损坏的图片。这个有用的函数能够帮助检测损坏图片并用你中意的图片替换它,并会将此问题通知给访客。这个还真有用,就是一些图片被删除了,或是不存在是,显示设置的默认图片替换。

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

检测复制、粘贴和剪切的操作

使用jQuery可以很容易去根据你的要求去检测复制、粘贴和剪切的操作。

$("#textA").bind('copy', function() {
$('span').text('copy behaviour detected!')}); $("#textA").bind('paste', function() {
$('span').text('paste behaviour detected!')}); $("#textA").bind('cut', function() {
$('span').text('cut behaviour detected!')});

遇到外部链接自动添加target=”blank”的属性

当链接到外部站点时,你可能使用target=”blank”的属性去在新界面中打开站点。问题在于target=”blank”属性并不是W3C有效的属性。让我们用jQuery来补救:下面这段代码将会检测是否链接是外链,如果是,会自动添加一个target=”blank”属性。

var root = location.protocol + '//' + location.host;
$('a').not(':contains(root)').click(function(){
    this.target = "_blank";});

在图片上停留时逐渐增强或减弱的透明效果

另一个“经典的”代码,它要放到你的工具箱里,因为你会不时地要实现它。

$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
    });});

在文本或密码输入时禁止空格键

在很多表格领域都不需要空格键,例如,电子邮件,用户名,密码等等等。这里是一个简单的技巧可以用于在选定输入中禁止空格键。

$('input.nospace').keydown(function(e) {
if (e.keyCode == 32) {
    return false;
}});


本文作者: Liaodeity

本文链接: https://www.jianbaizhan.com/article/391

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!


 请勿发布不友善或者负能量的内容。审查将对发布广告等违规信息进行处罚!