26 个 jQuery使用技巧

更新日期: 2019-03-13阅读: 2.5k标签: 技巧

1. 禁用右键点击(Disable right-click)

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



2. 禁用搜索文本框(Disappearing search field text)

$(document).ready(function() {
$("input.text1").val("Enter your search text here");
   textFill($(‘input.text1‘));
});

	function textFill(input){ //input focus text function
 	var originalvalue = input.val();
 	input.focus( function(){
  		if( $.trim(input.val()) == originalvalue ){ input.val(‘‘); }
 	});
 	input.blur( function(){
  		if( $.trim(input.val()) == ‘‘ ){ input.val(originalvalue); }
 	});
}


 

3. 新窗口打开链接(Opening links in a new window)

$(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. 检测浏览器(Detect browser)

$(document).ready(function() {
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
	// do something
}

// Target Safari
if( $.browser.safari ){
	// do something
}

// Target Chrome
if( $.browser.chrome){
	// do something
}

// Target Camino
if( $.browser.camino){
	// do something
}

// Target Opera
if( $.browser.opera){
	// do something
}

// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
	// do something
}

// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
	// do something
}
});


 

5. 预加载图片(Preloading images)

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


 

6. 样式筛选css Style switcher)

$(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" href="default.css" type="text/css">
// the links
<a href="#" class="Styleswitcher" rel="default.css">Default Theme</a>
<a href="#" rel="red.css">Red Theme</a>
<a href="#" class="Styleswitcher" rel="blue.css">Blue Theme</a>
});


 

7. 列高度相同(Columns of equal height)

$(document).ready(function() {
function equalHeight(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. 字体大小调整(Font resizing)

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

 

 

9. 返回页面顶部(Smooth(animated) page scroll)

$(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);
    return false;
   }
  }
  });
// 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坐标(Get the mouse cursor x and y axis)

$(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. 验证元素是否为空(Verify if an Element is empty)

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


 

13. 替换元素(Replace a element)

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

‘);
});


 

14. 延迟加载(jQuery timer callback functions)

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


 

15. 移除单词(Remove a word)

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


 

16. 验证元素是否存在(Verify that an element exists in jQuery)

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


 

17. 使整个DIV可点击(Make the entire 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切换(Switch between classes or id’s when resizing the window)

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



19. 克隆对象(Clone a object)

$(document).ready(function() {
   var cloned = $(‘#id‘).clone();
// how to use
<div id="id"></div>

});


 


20. 使元素居中屏幕(Center an element on the 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");
	  return this;
  }
  $("#id").center();
});



21. 自定义选择器(Write our own selector)

$(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 a element)

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



23. 自定义Bullets(Use Your Own Bullets)

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



24. 引用google分发的jQuery(Let Google host jQuery for you)

//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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></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 jQuery animations)

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



26. 防止不兼容冲突(No conflict-mode)

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

链接: https://www.fly63.com/article/detial/2359

微信小程序技巧_你需要知道的小程序开发技巧

一直以来进行了比较多的微信小程序开发... 总会接触到一些和官方组件或 api 相关或其无法解决的需求,于是决定在这里小小的整理一下微信小程序开发的一些技巧

微信小程序分享到朋友圈方法与技巧

小程序提供onShareAppMessage 函数,此函数只支持分享给我微信朋友,小程序如何分享到朋友圈呢?使用canvas绘制一张图片,并用wx.previewImage预览图片,然后长按图片保存图片到手机。

前端新手程序员不知道的 20个小技巧

前端新手程序员不知道的 20个小技巧:作为前端开发者,使用双显示器能大幅提高开发效率、学编程最好的语言不是PHP,是English、东西交付之前偷偷测试一遍、问别人之前最好先自己百度,google一下、把觉得不靠谱的需求放到最后做,很可能到时候需求就变了...

小技巧:检查你本地及公共 IP 地址

本地的 IP 地址是分配给你计算机上的内部硬件或虚拟网卡的本地/私有 IP 地址。根据你的 LAN 配置,上述 IP 地址可能是静态或动态的。公共的 IP 地址是你的 Internet 服务提供商(ISP)为你分配的公共/外部 IP 地址。

12 个 CSS 高级技巧汇总

使用 :not() 在菜单上应用/取消应用边框;给body添加行高;所有一切都垂直居中;逗号分隔的列表;使用负的 nth-child 选择项目;对图标使用SVG;优化显示文本;对纯CSS滑块使用 max-height;继承 box-sizing

提高网站加载速度的一些小技巧

为你网站的用户留下良好的第一印象是非常必要的。随着商业领域的竞争,拥有一个吸引人的网站可以帮助你脱颖而出。研究表明,如果加载时间超过3秒,会有 40% 的用户放弃访问你的网站

《CSS世界》中提到的实用技巧

清除浮动主要用于子元素浮动(float)之后,父元素无法撑起高度和宽度。文字少时居中,多时靠左因为div嵌套着p,所以p的尺寸并不会超过div。但是要注意,当p的内容为英文单词组成的时候

不常被提及的JavaScript小技巧

这次我们主要来分享11个在日常教程中不常被提及的JavaScript小技巧,他们往往在我们的日常工作中经常出现,但是我们又很容易忽略。Set类型是在ES6中新增的,它类似于数组,但是成员的值都是唯一的

CSS-in-JS 库 styled-class

为什么要在JavaScript里写CSS?避免命名全局污染,条件和动态样式(比如选择主题色之类的),在框架层面进行限制或补充(比如补全供应商前缀),避免业务人员使用奇技淫巧

新网站如何快速收录技巧

让新网站如何快速收录的方法教程较为简单,实施较为复杂。简单之处在于做好内容与外链(推荐友情链接),做好基础的url推送以及站内的优化设置即可

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!