最近寫了點小東西一個滑動驗證 ...
最近寫了點小東西一個滑動驗證
<html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0px; padding: 0px; } body{ background: #000000; } .sliding{ width: 400px; height: 40px; margin: 50px auto; background: #ccc; text-align: center; line-height: 40px; position: relative; } .sliding > p{ width: 0px; height: 100%; position: absolute; top: 0; left: 0; background: green; z-index: 99; color: #FFFFFF; text-align: center; overflow: hidden; } .sliding > span{ display: block; width: 46px; height: 100%; position: absolute; top: 0; left: 0; background-size: cover; cursor: pointer; z-index: 999; } .span1_back{ background: url(img/sli1.png) no-repeat center center; } .span2_back{ background: url(img/sli2.png)no-repeat center center; } </style> </head> <body> <div class="sliding"> 請按住滑塊,拖至最右側。 <p></p> <span class="span1_back"> </span> </div> <!-- 佈局方面主要是使用定位把p標簽和span都定位在 div 左邊 -->
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ $('.sliding > span').on('mousedown',function(ev){ var down_X=ev.clientX; //獲取滑鼠摁下的位置 var p_W=$('.sliding > p').get(0).offsetWidth; //獲取p的寬度當然這其實這個可有可無 var span_X=$('.sliding > span').get(0).offsetLeft; //與上同理 $(document).get(0).onmousemove=function(ev){ var move_X=ev.clientX; //獲取滑鼠移動的位置 var size = move_X - down_X + p_W; //用移動過後的位置減去滑鼠摁下的位置加上p的寬度或者 span 的left 值 因為倆者是同步的 所以 減去 其中一個就好 if(size>0){// 移動的時候判斷size>0的時候執行,Math.min選取最小值,讓拖動過程中不至於超出 size=Math.min(($('.sliding').get(0).offsetWidth - $('.sliding > span').get(0).offsetWidth),size); }else{ //小於0的時候 size =0; 防止有無聊的用戶拖回 超出邊界。 size=0; } $('.sliding > p').css('width', size + 'px'); $('.sliding > span').css('left', size + 'px'); return false;//防止拖拽過程中選中文字 } $(document).get(0).onmouseup=function(){ //滑鼠鬆開執行
//判段span到達邊界時候執行 if(($('.sliding > span').get(0).offsetLeft) >= ($('.sliding').get(0).offsetWidth - $('.sliding > span').get(0).offsetWidth)){ $('.sliding > span').attr('class','span2_back'); //更改span的背景圖片 $('.sliding > p').text('驗證通過'); //更改p標簽中的內容 $('.sliding > span').off('mousedown');//刪除滑鼠摁下方法防止用戶 無聊往回 推拽 }else{//判斷沒到達邊界讓它再回到起點 $('.sliding > span').animate({left:'0px'},300); //利用jquery讓p 和 span 回到起始狀態 $('.sliding > p').animate({width:'0px'},300); } $(document).get(0).onmousemove=null; //最後讓 滑鼠移動 和 滑鼠鬆開 事件停止 $(document).get(0).onmouseup=null; } }) }) </script> </body> </html>