關於js函式重構的問題
阿新 • • 發佈:2019-01-03
今天在走獲得焦點動作時,想著去重構一下獲得和失去焦點的程式碼,重構前:
重構後:$(".searchInput").focus(function(){ $(".search").css("width","320px"); $(".searchInput").css({"width":"268px","border":"none","outline":"none"}); $(".searchHidden").css("display","block"); $(".searchbtn").css({"background-color":"#969696","color":"white"}); }); $(".searchInput").blur(function(){ $(".search").css("width","240px"); $(".searchInput").css({"width":"188px","border-style":"none"}); $(".searchHidden").css("display","none"); });
遇到的問題是:剛開始我直接這樣子寫,沒有在為onfocus建立一個函式,所以解析器是直接呼叫了changeInputDiv函式,並不能表現出獲得焦點和失去焦點的變化。沒有點選時就已經呼叫了這個函式,而獲得焦點和失去時就不再有反應。$(".searchInput").focus(function(){ changeInputDiv("320px","268px","block","#969696","white") }); $(".searchInput").blur(function(){ changeInputDiv("240px","188px","none","#eeeeee","#969696") }); function changeInputDiv(width1,width2,display,bakcolor,color){ $(".search").css("width",width1); $(".searchInput").css("width",width2); $(".searchHidden").css("display",display); $(".searchbtn").css({"background-color":bakcolor,"color":color}); }
$(".searchInput").onfocus=changeInputDiv("320px","268px","block","#969696","white");