几个常用的JS代码

来源:互联网 发布:java跨域上传图片 编辑:程序博客网 时间:2024/04/19 22:49
jQuery平滑回到顶端效果
    html:
    <h1 id="anchor">页面标题</h1>
    <div id="container">页面内容</div>
    <p><a href="#anchor" class="topLink">回到顶端</a></p>
    css:
    #container{
   height: 1000px;
   line-height: 1000px;
   text-align: center;
   font-family: Arial;
   border: 1px solid #EEEEEE;
    }

    .topLink{
  float:right;
  padding:10px;
  color: #CCC;
    }
js:
$(document).ready(function() {

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

});



jQuery测试密码强度
html:
密码:<input type="password" id="pass" value />
<div id="passstrength"></div>
css:
#passstrength{
  font-family: Arial;
  margin: 20px 0px;
}

.ok{
  color: green;
}

.alert{
  color: orange;
}

.error{
  color: red;
}
js:
$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('密码字符太少');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').attr('class', 'ok');
             $('#passstrength').html('密码强度很好!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').attr('class', 'alert');
             $('#passstrength').html('密码强度中等!');
     } else {
             $('#passstrength').attr('class', 'error');
             $('#passstrength').html('密码强度太弱!');
     }
     return true;
});

jQuery实现的DIv高度保持一致
html:
<div id="div1">
  <div style="margin:20px;">DIV层1</div>
</div>
<div id="div2">
  <div style="margin:20px;">DIV层2</div>
</div>
css:
#div1{
  height: 800px;
  float:left;
  width: 60%;
  background: #EEE;
  text-align:center;
}

#div2{
  height: 600px;
  float:right;
  width: 35%;
  background: #EEE;
  text-align:center;
}
js:
var maxHeight = 0;

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

$("div").height(maxHeight);


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); 
});
0 0