1. 程式人生 > >前端系列教程之JS(自認為有用程式碼)

前端系列教程之JS(自認為有用程式碼)

以下程式碼並不唯一,僅供參考

1.保證自己的頁面不被嵌入其他框架

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>保證自己的頁面不被嵌入其他框架</title>
	</head>
	<body>
	<script>
	//判斷當前頁面是否為頂層,如果不是則將當前頁面設定為頂層
		if(self != top){
		//(當然我們也可以修改此處的內容,對返回結果進行設定)
			top.location=self.location;
		}
	</script>
	</body>
</html>

2.離開頁面時彈出確認對話方塊

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>離開頁面時彈出確認對話方塊</title>
	</head>
	<body>
	<script>
		window.onbeforeunload =function(){
			return "確認退出?";
		}
	</script>
	</body>
</html>

4.禁止文字的複製與貼上

<!DOCTYPE html>
	<head>
	    <title>禁止複製與貼上</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	</head>
	<body id='banCopyPaste'>
		<h2>禁止複製與貼上</h2>
		<script type="text/javascript">
		    var banCopyPaste = document.getElementById("banCopyPaste");
		    banCopyPaste.oncopy = function(){		//禁止複製事件
		        return false;
		    }
		    banCopyPaste.onpaste = function(){		//禁止貼上
		        return false;
		    }
		</script>
	</body>
</html>

5.密碼強度實時驗證

<!DOCTYPE html>
<head>
    <title>密碼強度實時驗證</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<h2>密碼強度實時驗證</h2>
	<input id="passwordStrength" data-hint='請輸入密碼' type="password">    
	<span id="showStrength"></span>
	<script type="text/javascript">
	    window.onload = function(){
	        function setCss(_this, cssOption){//設定樣式
	            if ( !_this || _this.nodeType === 3 || _this.nodeType === 8 || !_this.style ) {
	                return;
	            }
	            for(var cs in cssOption){
	                _this.style[cs] = cssOption[cs];
	            }
	            return _this;
	        }
	
	        function trim(chars){//去除字串左右兩邊的空格
	            return (chars || "").replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );
	        }
	
	        function passwordStrength(passwordStrength, showStrength){
	            var self = this;
	            /*字元權重:
	             數字1,字母2 ,其他字元為3
	             當密碼長度小於6為不符合標準,
	             長度大=6強度小於10,強度弱
	             ,長度大=6 強度>=10 <15,強度中,
	             長度大=6 強度>=15 強*/
	            passwordStrength.onkeyup = function(){
	                var _color = ["red", "yellow", "orange", "green"],
	                        msgs = ["密碼太短","弱","中","強"],
	                        _strength= 0,
	                        _v = trim(passwordStrength.value)
	                _vL = _v.length,
	                        i = 0;
	
	                var charStrength = function(char){//計算單個字元強度
	                    if (char>=48 && char <=57){ //數字
	                        return 1;
	                    }
	                    if (char>=97 && char <=122) {//小寫
	                        return 2;
	                    }else{
	                        return 3; //特殊字元
	                    }
	                }
	
	                if(_vL < 6){//計算模式
	                    showStrength.innerText = msgs[0];
	                    setCss(showStrength, {
	                        "color":_color[0]
	                    })
	                }else{
	                    for( ; i < _vL ; i++){
	                        _strength+=charStrength(_v.toLocaleLowerCase().charCodeAt(i));
	                    }
	                    if(_strength < 10){
	                        showStrength.innerText = msgs[1];
	                        setCss(showStrength, {
	                            "color":_color[1]
	                        })
	                    }
	                    if(_strength >= 10 && _strength < 15){
	                        showStrength.innerText = msgs[2];
	                        setCss(showStrength, {
	                            "color":_color[2]
	                        })
	                    }
	                    if(_strength >= 15){
	                        showStrength.innerText = msgs[3];
	                        setCss(showStrength, {
	                            "color":_color[3]
	                        })
	                    }
	                }
	            }
	        }
	        passwordStrength(
	                document.getElementById("passwordStrength"),
	                document.getElementById("showStrength"));
	    };
	</script>
</body>
</html>

6.驗證輸入是否為空

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h2>驗證是否輸入</h2>
		<input type='text' id='strs'>
		<input type='button' id='isContent' value='驗證是否為空'><br>
		<script type="text/javascript">
				var isContent = document.getElementById("isContent");
				var strs = document.getElementById("strs");
				isContent.onclick = function(){
					if(!strs.value.replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" )){
						alert("您的輸入為空!");
					}else{
						alert("您的輸入不為空!");
					}
				}		
		</script>
	</body>
</html>

7.回車提交效果

<!DOCTYPE html>
<head>
    <title>回車提交效果</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<h2>回車提交</h2>
	<input type="text" id="enterSubmit" value="回車提交">
	<script type="text/javascript">
	    window.onload = function(){
	        document.getElementById("enterSubmit").onkeyup = function(e){
	            e = e || window.event;
	            var keycode = e.keyCode || e.which ||e.charCode;
	            if(keycode === 13){
	                alert("回車提交成功");
	            }
	
	        }
	    };
	</script>
</body>
</html>

8.TextArea自適應文字行數

<!DOCTYPE HTML>
<head>
    <title>TextArea自適應文字行數</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<h2>TextArea自適應文字行數</h2>
	<textarea rows=1 name=s1 cols=27 id="autoRow"></textarea>
	<script type="text/javascript">
		window.onload = function(){
			var autoRow = document.getElementById("autoRow");
			autoRow.style.overflowY = "hidden";
			autoRow.onkeyup= function(){
				autoRow.style.height = autoRow.scrollHeight;
			};
		};
	</script>
</body>
</html>

9.Checkbox全選、取消全選、反選

<!DOCTYPE HTML>
<head>
    <title>Checkbox全選、取消全選、反選</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<h2>Checkbox全選、取消全選、反選</h2>
	<p><input type="button" id='allSelect' value="全選"><input type="button" id='canelallSelect' value="取消全選"><input type="button" id='_select' value='反選'> </p>
	<input type="checkbox" name='actionSelects'>1<br />
	<input type="checkbox" name='actionSelects'>2<br />
	<input type="checkbox" name='actionSelects'>3<br />
	<input type="checkbox" name='actionSelects'>4<br />
	<script type="text/javascript">
		window.onload = function(){
			var targets = document.getElementsByName("actionSelects"),
					targetsLen = targets.length,
					i = 0;

			document.getElementById("allSelect").onclick = function(){
				for(i = 0 ;i < targetsLen ; i ++){
					targets[i].checked = true;
				}
			}

			document.getElementById("canelallSelect").onclick = function(){
				for(i = 0 ;i < targetsLen ; i ++){
					targets[i].checked = false;
				}
			}

			document.getElementById("_select").onclick = function(){
				for(i = 0 ; i < targetsLen ; i ++){
					targets[i].checked = !targets[i].checked;
				}

			}
		};
	</script>
</body>
</html>

10.下拉框聯動效果

<!DOCTYPE HTML>
<head>
    <title>2.33節,下拉框聯動效果</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
	<h2>下拉框聯動效果</h2>
	<p>
		省級:
		<select id="provinces">
		</select>
	</p>
	<p>
		市級:
		<select id="citys">
		</select>
	</p>
	<script type="text/javascript">
		window.onload = function(){
			var linkDatas = {
				provinces:[
					{"code":"0","name":"請選擇"},
					{"code":"1","name":"北京"},
					{"code":"2","name":"天津"},
					{"code":"3","name":"河北"},
					{"code":"4","name":"湖北"},
					{"code":"5","name":"廣東"},
					{"code":"6","name":"其他"}
				],
				citys:{
					0:["請選擇"],
					1:["朝陽區","海淀區","東城區","西城區","房山區","其他"],
					2:["天津"],
					3:["滄州","石家莊","秦皇島","其他"],
					4:["武漢市","宜昌市","襄樊市","其他"],
					5:["廣州市","深圳市","汕頭市","佛山市","珠海市","其他"],
					6:["其他"]
				}
			};
			function addOptions(target, optons){
				var _option = null,
						ol = optons.length,
						i = 0,
						_v = "",
						_t = "";
				for(; i < ol ; i++ ){
					_v = optons[i].value;
					_t = optons[i].text;
					_option = document.createElement("OPTION")
					_option.value = _v;
					_option.text = _t;
					target.options.add(_option);
				}
			}

			function linkage(parents, childs){//聯動效果,業務處理---引數(一級選單,二級選單)
				var  _linkDatas = linkDatas,
						_parents = _linkDatas.provinces,
						_childs = _linkDatas.citys,
						_initCity = _childs[0],
						_p = [];
				/*初始化資料*/

				for(var i in _parents){//省
					_p.push({
						"text" : _parents[i].name,
						"value" : _parents[i].code
					});
				}

				addOptions(parents, _p);//新增選項

				addOptions(childs,[{//城市
					"value":_initCity,
					"text":_initCity
				}]);

				parents.onchange = function(){//聯動事件繫結及具體業務處理
					var __childs = _childs[this.value],
							__childsLen = __childs.length,
							l = 0,
							__p = [];
					childs.innerHTML = "";
					for(; l < __childsLen ; l++){
						__p.push({
							"value" : __childs[l],
							"text" : __childs[l]
						});
					}
					addOptions(childs, __p);
				}

			}

			linkage(//繫結一級選單與二級選單
					document.getElementById("provinces"),
					document.getElementById("citys"));
		};
	</script>
</body>
</html>