您的位置:首页 > Web前端 > JQuery

jquery常用代码片段

2011-07-30 16:16 441 查看
1)判断一个元素是否存在

使用jQuery判断元素是否存在,非常的简单。对于一个jQuery对象,我们只需要用length属性即可判断元素是否存在,如果存在肯定是大于0,示例代码:

判断这个图片是否存在,如果存在在把这个图片替换

<img src="http://www.jquery001.com/images/demo/2010/anyixuan.jpg" style="  float:right" id='uu2'>

<script type="text/javascript">
$(document).ready(function() {
if($('#uu2').length>0){
$('#uu2').attr("src", "http://www.blogkid.cn/wp-content/uploads/2008/04/memcached_shell_2.JPG");
}
});

</script>


2)获得文本框焦点,主要使用focus 获得焦点

<input type="text" id="txtUser" style="width:200px; " />


$('#txtUser').bind("focus",function(){
$(this).animate({ width: "500px" }, 1000);
})
$('#txtUser').bind("blur",function(){
$(this).height("120px");
})
});


3)对失效的图片的处理  主要使用error 方法,注意在ie下不兼容性,当图片失效的时候,我们可以直接移除该图片,也可以替换该图片

<img src="mooncake1.jpg" alt="mooncake" />
<p>中秋节我们吃月饼</p>

$(document).ready(function() {
$("img").error(function() {
$(this).remove();   //1.remove the image
$(this).attr("src", "no-image.jpg");    //2.replace the image
});
});


4)


jQuery 判断图像是否被完全加载进来

$("#demoImg").attr("src", "demo.jpg").load(function() {
alert("图片加载完成");
});


5)


jQuery 判断浏览器类型及版本号

var browserName = navigator.userAgent.toLowerCase();
mybrowser = {
version: (browserName.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
safari: /webkit/i.test(browserName) && !this.chrome,
opera: /opera/i.test(browserName),
firefox: /firefox/i.test(browserName),
msie: /msie/i.test(browserName) && !/opera/.test(browserName),
mozilla: /mozilla/i.test(browserName) && !/(compatible|webkit)/.test(browserName) && !this.chrome,
chrome: /chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)
}
$(document).ready(function () {
if (mybrowser.msie) {
alert("浏览器为:Internet Explorer 版本号为:" + $.browser.version);
}
else if (mybrowser.mozilla) {
alert("浏览器为:Firefox 版本号为:" + $.browser.version);
}
else if (mybrowser.opera) {
alert("浏览器为:Opera 版本号为:" + $.browser.version);
}
else if (mybrowser.safari) {
alert("浏览器为:Safari 版本号为:" + $.browser.version);
}
else if (mybrowser.chrome) {
alert("浏览器为:Chrome 版本号为:" + mybrowser.version);
}
else {
alert("神马");
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息