高效Web开发的10个jQuery代码片段

2020-05-19 07:42:59易采站长站整理


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

7、检测复制、粘贴和剪切的操作
 
使用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!')
});

8、遇到外部链接自动添加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";
});

9、在图片上停留时逐渐增强或减弱的透明效果
 另一个“经典的”代码,它要放到你的工具箱里,因为你会不时地要实现它。


$(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、在文本或密码输入时禁止空格键
 在很多表格领域都不需要空格键,例如,电子邮件,用户名,密码等等等。这里是一个简单的技巧可以用于在选定输入中禁止空格键。


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