js面向過程與面向物件程式設計示例(使用jquery庫)
阿新 • • 發佈:2019-01-28
<!DOCTYPE html> <html> <head> <style type="text/CSS"> .firstDiv{ float:left; background:pink;} .firstDiv:hover{ cursor:pointer;} .noSelected{ -moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none;} .secondDiv{ background:gray; width:200px; height:400px; float:left; display:none; padding-top:30px; padding-left:30px;} </style> </head> <body> <div id="firstDiv" class="firstDiv"><span class="noSelected">滑鼠滑動檢視資訊。</span></div> <div id="secondDiv" class="secondDiv"> <p>qq:1900098</p> <p>tel:99998888</p> <p>user:xq</p> </div> <script type="text/JavaScript" src="../publicJQuery/jquery-2.1.4.js"></script> <script type="text/JavaScript"> /*面向過程程式設計,首先得到某某,然後執行某某操作,敘事般往下走 $("#firstDiv").hover(function(){$("#secondDiv").css("display","block");} , function(){$("#secondDiv").css("display","none");}); $("#secondDiv").hover(function(){$("#secondDiv").css("display","block");} , function(){$("#secondDiv").css("display","none");}); */ /*建立一個showAndHideDiv物件,屬性為傳入的引數,方法為show()跟hide()方法*/ function showAndHideDiv(element){ /* 不明顯的面向物件 this.show=function(){ $(element).css("display","block"); } this.hide=function(){ $(element).css("display","none"); } */ this.element=element; } showAndHideDiv.prototype={ show:function(){ $(this.element).css("display","block"); }, hide:function(){ $(this.element).css("display","none"); } } var divForChange=new showAndHideDiv("#secondDiv"); $("#firstDiv,#secondDiv").hover(function(){divForChange.show();} ,function(){divForChange.hide();}); //$("#secondDiv").hover( function(){divForChange.show();}, function(){divForChange.hide();}); </script> </body> </html>