首页 >图片操作 > 内容

jQuery 代码片段积累1( 9 + 15 +26 )

2023年9月30日 20:33


三:July21

1. 禁止右键点击

$(document).ready(function(){    $(document).bind("contextmenu",function(e){        returnfalse;    });});

2. 隐藏搜索文本框文字

Hide when clicked in the search field, the value.(example can be found below in the comment fields)

$(document).ready(function() {$("input.text1").val("Enter your search text here");   textFill($('input.text1'));});      functiontextFill(input){//input focus text function    varoriginalvalue = input.val();    input.focus(function(){        if( $.trim(input.val()) == originalvalue ){ input.val(''); }    });    input.blur(function(){        if( $.trim(input.val()) == ''){ input.val(originalvalue); }    });}


3. 在新窗口中打开链接

XHTML 1.0 Strict doesn’t allow this attribute in the code, so use this to keep the code valid.

$(document).ready(function() {   //Example 1: Every link will open in a new window   $('a[href^="http://"]').attr("target","_blank");     //Example 2: Links with the rel="external" attribute will only open in a new window   $('a[@rel$='external']').click(function(){      this.target = "_blank";   });});// how to use<A href="http://www.opensourcehunter.com" rel=external>open link</A>

4. 检测浏览器

注: 在版本jQuery 1.4中,$.support 替换掉了$.browser 变量

$(document).ready(function() {// Target Firefox 2 and aboveif($.browser.mozilla && $.browser.version >= "1.8"){    // do something} // Target Safariif( $.browser.safari ){    // do something} // Target Chromeif( $.browser.chrome){    // do something} // Target Caminoif( $.browser.camino){    // do something} // Target Operaif( $.browser.opera){    // do something} // Target IE6 and belowif($.browser.msie && $.browser.version <= 6 ){    // do something} // Target anything above IE6if($.browser.msie && $.browser.version > 6){    // do something}});

5. 预加载图片

This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.

$(document).ready(function() {jQuery.preloadImages = function(){  for(vari = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);  }}});// how to use$.preloadImages("image1.jpg");

6. 页面样式切换

$(document).ready(function() {    $("a.Styleswitcher").click(function() {        //swicth the LINK REL attribute with the value in A REL attribute        $('link[rel=stylesheet]').attr('href', $(this).attr('rel'));    });});// how to use// place this in your header<LINK rel=stylesheet type=text/css href="default.css">// the links<A class=Styleswitcher href="#"rel=default.css>Default Theme</A><A class=Styleswitcher href="#"rel=red.css>Red Theme</A><A class=Styleswitcher href="#"rel=blue.css>Blue Theme</A>


7. 列高度相同

如果使用了两个CSS列,使用此种方式可以是两列的高度相同。

$(document).ready(function() {functionequalHeight(group) {    tallest = 0;    group.each(function() {        thisHeight = $(this).height();        if(thisHeight > tallest) {            tallest = thisHeight;        }    });    group.height(tallest);}});// how to use$(document).ready(function() {    equalHeight($(".left"));    equalHeight($(".right"));});


8. 动态控制页面字体大小

用户可以改变页面字体大小

$(document).ready(function() {  // Reset the font size(back to default)  varoriginalFontSize = $('html').css('font-size');    $(".resetFont").click(function(){    $('html').css('font-size', originalFontSize);  });  // Increase the font size(bigger font0  $(".increaseFont").click(function(){    varcurrentFontSize = $('html').css('font-size');    varcurrentFontSizeNum = parseFloat(currentFontSize, 10);    varnewFontSize = currentFontSizeNum*1.2;    $('html').css('font-size', newFontSize);    returnfalse;  });  // Decrease the font size(smaller font)  $(".decreaseFont").click(function(){    varcurrentFontSize = $('html').css('font-size');    varcurrentFontSizeNum = parseFloat(currentFontSize, 10);    varnewFontSize = currentFontSizeNum*0.8;    $('html').css('font-size', newFontSize);    returnfalse;  });});

9. 返回页面顶部功能

For a smooth(animated) ride back to the top(or any location).

$(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) {  vartargetOffset = $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>

11. 获得鼠标指针XY值

Want to know where your mouse cursor is?

$(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>


12. 验证元素是否为空

This will allow you to check if an element is empty.

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



13. 替换元素

Want to replace a div, or something else?

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

14. jQuery延时加载功能

Want to delay something?

$(document).ready(function() {   window.setTimeout(function() {     // do something   }, 1000);});

15. 移除单词功能

Want to remove a certain word(s)?

$(document).ready(function() {   varel = $('#id');   el.html(el.html().replace(/word/ig,""));});

16. 验证元素是否存在于jquery对象集合中

Simply test with the .length property if the element exists.

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

17. 使整个DIV可点击

Want to make the complete div clickable?

$(document).ready(function() {    $("div").click(function(){      //get the url from href attribute and launch the url      window.location=$(this).find("a").attr("href");  return false;    });});// how to use<DIV><A href="index.html">home</A></DIV>

18. ID与Class之间转换.

当改变Window大小时,在ID与Class之间切换

$(document).ready(function() {   functioncheckWindowSize() {    if( $(window).width() > 1200 ) {        $('body').addClass('large');    }    else{        $('body').removeClass('large');    }   }$(window).resize(checkWindowSize);});

19. 克隆对象

Clone a div or an other element.

$(document).ready(function() {   varcloned = $('#id').clone();});// how to use<DIV id=id></DIV>

20. 使元素居屏幕中间位置

Center an element in the center of your screen.

$(document).ready(function() {  jQuery.fn.center = function() {      this.css("position","absolute");      this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");      this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");      returnthis;  }  $("#id").center();});

21. 写自己的选择器

Write your own selectors.

$(document).ready(function() {   $.extend($.expr[':'], {       moreThen1000px:function(a) {           return$(a).width() > 1000;      }   });  $('.box:moreThen1000px').click(function() {      // creating a simple js alert box      alert('The element that you have clicked is over 1000 pixels wide');  });});

22. 统计元素个数

Count an element.

$(document).ready(function() {   $("p").size();});

23. 使用自己的 Bullets

Want to use your own bullets instead of using the standard or images bullets?

$(document).ready(function() {   $("ul").addClass("Replaced");   $("ul > li").prepend("‒ "); // how to use ul.Replaced { list-style : none; }});

24. 引用Google主机上的Jquery类库

Let Google host the jQuery script for you. This can be done in 2 ways.

//Example 1<SCRIPT src="http://www.google.com/jsapi"></SCRIPT><SCRIPT type=text/javascript>google.load("jquery","1.2.6");google.setOnLoadCallback(function() {    // do something});</SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>  // Example 2:(the best and fastest way)<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

25. 禁用Jquery(动画)效果

Disable all jQuery effects

$(document).ready(function() {    jQuery.fx.off = true;});

26. 与其他Javascript类库冲突解决方案

To avoid conflict other libraries on your website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign.

$(document).ready(function() {   var$jq = jQuery.noConflict();   $jq('#id').show();});







二:July16

http://www.csdn.net/article/2013-07-16/2816238-15-jQuery-Code-Snippets-for-Developers

1.预加载图片

1
2
3
4
5
6
7
8
9
10
11
12
( function ($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function () {
var args_len = arguments.length;
for ( var i = args_len; i--;) {
var cacheImage = document.createElement( 'img' );
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
jQuery.preLoadImages( "image1.gif" , "/path/to/image2.png" );
源码

2. 让页面中的每个元素都适合在移动设备上展示

1
2
3
4
5
6
7
8
9
10
11
var scr = document.createElement( 'script' );
document.body.appendChild(scr);
scr.onload = function (){
$( 'div' ).attr( 'class' , '' ).attr( 'id' , '' ).css({
'margin' : 0,
'padding' : 0,
'width' : '100%' ,
'clear' : 'both'
});
};
源码

3.图像等比例缩放

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
$(window).bind( "load" , function () {
// IMAGE RESIZE
$( '#product_cat_list img' ).each( function () {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $( this ).width();
var height = $( this ).height();
if (width > maxWidth){
ratio = maxWidth / width;
$( this ).css( "width" , maxWidth);
$( this ).css( "height" , height * ratio);
height = height * ratio;
}
var width = $( this ).width();
var height = $( this ).height();
if (height > maxHeight){
ratio = maxHeight / height;
$( this ).css( "height" , maxHeight);
$( this ).css( "width" , width * ratio);
width = width * ratio;
}
});
//$("#contentpage img").show();
// IMAGE RESIZE
});
源码

4.返回页面顶部

1
2
3
4
5
6
7
8
// Back To Top
$(document).ready( function (){
$( '.top' ).click( function () {
$(document).scrollTo(0,500);
});
});
//Create a link defined with the class .top
<a href= "#" class= "top" >Back To Top</a>
源码

5.使用jQuery打造手风琴式的折叠效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var accordion = {
init: function (){
var $container = $( '#accordion' );
$container.find( 'li:not(:first) .details' ).hide();
$container.find( 'li:first' ).addClass( 'active' );
$container.on( 'click' , 'li a' , function (e){
e.preventDefault();
var $ this = $( this ).parents( 'li' );
if ($ this .hasClass( 'active' )){
if ($( '.details' ).is( ':visible' )) {
$ this .find( '.details' ).slideUp();
} else {
$ this .find( '.details' ).slideDown();
}
} else {
$container.find( 'li.active .details' ).slideUp();
$container.find( 'li' ).removeClass( 'active' );
$ this .addClass( 'active' );
$ this .find( '.details' ).slideDown();
}
});
}
};

6.通过预加载图片廊中的上一幅下一幅图片来模仿Facebook的图片展示方式

1
2
3
4
5
6
7
8
var nextimage = "/images/some-image.jpg" ;
$(document).ready( function (){
window.setTimeout( function (){
var img = $( "" ).attr( "src" , nextimage).load( function (){
//all done
});
}, 100);
});

源码

7.使用jQuery和Ajax自动填充选择框

1
2
3
4
5
6
7
8
9
10
11
12
13
$( function (){
$( "select#ctlJob" ).change( function (){
$.getJSON( "/select.php" ,{id: $( this ).val(), ajax: 'true' }, function (j){
var options = '' ;
for ( var i = 0; i < j.length; i++) {
options += '
' + j[i].optionDisplay + '
' ;
}
$( "select#ctlPerson" ).html(options);
})
})
})
源码

8.自动替换丢失的图片

1
2
3
4
5
6
7
8
// Safe Snippet
$( "img" ).error( function () {
$( this ).unbind( "error" ).attr( "src" , "missing_image.gif" );
});
// Persistent Snipper
$( "img" ).error( function () {
$( this ).attr( "src" , "missing_image.gif" );
});

源码

9.在鼠标悬停时显示淡入/淡出特效

1
2
3
4
5
6
7
8
$(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
});
});
源码

10.清空表单数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$( ':input' , form).each( function () {
var type = this .type;
var tag = this .tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text ' || type == ' password ' || tag == ' textarea ')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their ' value ' changed
else if (type == ' checkbox ' || type == ' radio ')
this.checked = false;
// select elements need to have their ' selectedIndex ' property set to -1
// (this works for both single and multiple select elements)
else if (tag == ' select')
this .selectedIndex = -1;
});
};
源码

11.预防对表单进行多次提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready( function () {
$( 'form' ).submit( function () {
if ( typeof jQuery.data( this , "disabledOnSubmit" ) == 'undefined' ) {
jQuery.data( this , "disabledOnSubmit" , { submited: true });
$( 'input[type=submit], input[type=button]' , this ).each( function () {
$( this ).attr( "disabled" , "disabled" );
});
return true ;
}
else
{
return false ;
}
});
});
源码

12.动态添加表单元素

1
2
3
4
5
//change event on password1 field to prompt new input
$( '#password1' ).change( function () {
//dynamically create new input and insert after password1
$( "#password1" ).append( "" );
});
源码

13.让整个Div可点击

1
2
blah blah blah. link
The following lines of jQuery will make the entire div clickable: $( ".myBox" ).click( function (){ window.location=$( this ).find( "a" ).attr( "href" ); return false ; });
源码

14.平衡高度或Div元素

1
2
3
4
5
var maxHeight = 0;
$( "div" ).each( function (){
if ($( this ).height() > maxHeight) { maxHeight = $( this ).height(); }
});
$( "div" ).height(maxHeight);
源码

15. 在窗口滚动时自动加载内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var loading = false ;
$(window).scroll( function (){
if ((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
if (loading == false ){
loading = true ;
$( '#loadingbar' ).css( "display" , "block" );
$.get( "load.php?start=" +$( '#loaded_max' ).val(), function (loaded){
$( 'body' ).append(loaded);
$( '#loaded_max' ).val(parseInt($( '#loaded_max' ).val())+50);
$( '#loadingbar' ).css( "display" , "none" );
loading = false ;
});
}
}
});
$(document).ready( function () {
$( '#loaded_max' ).val(50);
});


一:July12

转自:http://www.w3cfuns.com/article-5597822-1-1.html


1.jQuery平滑回到顶端效果

$(document).ready(function() {        $("a.topLink").click(function() {          $("html, body").animate({              scrollTop: $($(this).attr("href")).offset().top + "px"          }, {              duration: 500,              easing: "swing"          });          return false;      });    });  


2.jQuery处理图片尺寸

$(window).bind("load", function() {      // 图片修改大小      $('#imglist img').each(function() {          var maxWidth = 120;          var maxHeight = 120;          var ratio = 0;          var width = $(this).width();          var height = $(this).height();                if(width > maxWidth){              ratio = maxWidth / width;              $(this).css("width", maxWidth);              $(this).css("height", height * ratio);              height = height * ratio;          }                  if(height > maxHeight){              ratio = maxHeight / height;              $(this).css("height", maxHeight);              $(this).css("width", width * ratio);              width = width * ratio;          }      });    });

3.jQuery实现的滚动自动加载代码

var loading = false;  $(window).scroll(function(){      if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){          if(loading == false){              loading = true;              $('#loadingbar').css("display","block");              $.get("load.php?start="+$('#loaded_max').val(), function(loaded){                  $('body').append(loaded);                  $('#loaded_max').val(parseInt($('#loaded_max').val())+50);                  $('#loadingbar').css("display","none");                  loading = false;              });          }      }  });    $(document).ready(function() {      $('#loaded_max').val(50);  });  

4.jQuery测试密码强度

$('#pass').keyup(function(e) {       var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*[        DISCUZ_CODE_372        ]quot;, "g");       var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*[        DISCUZ_CODE_372        ]quot;, "g");       var enoughRegex = new RegExp("(?=.{6,}).*", "g");       if (false == enoughRegex.test($(this).val())) {               $('#passstrength').html('More Characters');       } else if (strongRegex.test($(this).val())) {               $('#passstrength').className = 'ok';               $('#passstrength').html('Strong!');       } else if (mediumRegex.test($(this).val())) {               $('#passstrength').className = 'alert';               $('#passstrength').html('Medium!');       } else {               $('#passstrength').className = 'error';               $('#passstrength').html('Weak!');       }       return true;  });  

5.jQuery实现的DIv高度保持一致

var maxHeight = 0;    $("div").each(function(){     if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }  });    $("div").height(maxHeight);  


6.简单处理IE6上PNG格式文件

$('.pngfix').each( function() {     $(this).attr('writing-mode', 'tb-rl');     $(this).css('background-image', 'none');     $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');  });  
将class=pngfix添加到需要处理的对象即可。


7.jQuery处理JSON

function parseJson(){      //Start by calling the json object, I will be using a           //file from my own site for the tutorial       //Then we declare a callback function to process the data      $.getJSON('hcj.json',getPosts);         //The process function, I am going to get the title,           //url and excerpt for 5 latest posts      function getPosts(data){             //Start a for loop with a limit of 5           for(var i = 0; i < 5; i++){              //Build a template string of                           //the post title, url and excerpt              var strPost = '<h2>'                         + data.posts[i].title                        + '</h2>'                        + '<p>'                        + data.posts[i].excerpt                        + '</p>'                        + '<a href="'                        + data.posts[i].url                        + '" title="Read '                        + data.posts[i].title                        + '">Read ></a>';                 //Append the body with the string              $('body').append(strPost);             }      }     }     //Fire off the function in your document ready  $(document).ready(function(){      parseJson();                     });  

8.jQuery实现让整个div可以被点击

$(".myBox").click(function(){      window.location=$(this).find("a").attr("href");       return false; });

9.jQuery实现的Facebook风格的图片预加载效果

var nextimage = "http://www.gbtags.com/gb/networks/uploadimgthumb/55d67b14-fb25-45e7-acc8-211a41047ef0.jpg";  $(document).ready(function(){    window.setTimeout(function(){      var img = $("<img>").attr("src", nextimage).load(function(){       $('div').append(img);      });    }, 100);  });  



















参考文章:https://blog.csdn.net/null____/article/details/9309685

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时候联系我们修改或删除,在此表示感谢。

特别提醒:

1、请用户自行保存原始数据,为确保安全网站使用完即被永久销毁,如何人将无法再次获取。

2、如果上次文件较大或者涉及到复杂运算的数据,可能需要一定的时间,请耐心等待一会。

3、请按照用户协议文明上网,如果发现用户存在恶意行为,包括但不限于发布不合适言论妄图

     获取用户隐私信息等行为,网站将根据掌握的情况对用户进行限制部分行为、永久封号等处罚。

4、如果文件下载失败可能是弹出窗口被浏览器拦截,点击允许弹出即可,一般在网址栏位置设置

5、欢迎将网站推荐给其他人,网站持续更新更多功能敬请期待,收藏网站高效办公不迷路。

      



登录后回复

共有0条评论