Creating Custom Functions · Issue #637 · less/less.js - GitHub
文章推薦指數: 80 %
Hi, It would be nice to define Custome Functions like: darkfadein(@color ... However if it is calling 3 less functions with specific values, ... Skiptocontent {{message}} less / less.js Public Notifications Fork 3.5k Star 16.8k Code Issues 160 Pullrequests 14 Discussions Actions Security Insights More Code Issues Pullrequests Discussions Actions Security Insights Newissue Haveaquestionaboutthisproject?SignupforafreeGitHubaccounttoopenanissueandcontactitsmaintainersandthecommunity. Pickausername EmailAddress Password SignupforGitHub Byclicking“SignupforGitHub”,youagreetoourtermsofserviceand privacystatement.We’lloccasionallysendyouaccountrelatedemails. AlreadyonGitHub? Signin toyouraccount Jumptobottom CreatingCustomFunctions #637 Closed Deltachaosopenedthisissue Feb16,2012 ·28comments Closed CreatingCustomFunctions #637 Deltachaosopenedthisissue Feb16,2012 ·28comments Labels considerclosing featurerequest lowpriority Comments Copylink Deltachaos commented Feb16,2012 Hi, ItwouldbenicetodefineCustomeFunctionslike: darkfadein(@color,@value){ returnfadein(darken(@color,@value)); } .foo{ color:darkfadein(#333,10%); } shouldbecompiledto: .foo{ color:#1a1a1a; } Thetextwasupdatedsuccessfully,buttheseerrorswereencountered: 👍 16 afc163,toastal,micalevisk,mbaev,freedom-git,chfumero,Walkeryr,Macadoshis,aviram83,PredokMiF,and6morereactedwiththumbsupemoji Allreactions 👍 16reactions Copylink souldreamer commented Feb16,2012 Maybetodifferentiateitfromamix-inandkeepclosertoCSSsyntax,itcouldbe: @darkfadein(@color,@value):fadein(darken(@color,@value)); Kindoflikeavariablethatdependsonparameters(whichifyouthinkoniskindofafunction=) Allreactions Sorry,somethingwentwrong. Copylink alpha123 commented Feb17,2012 +1to@souldreamer'ssyntax. Allreactions Sorry,somethingwentwrong. Copylink Author Deltachaos commented Feb18,2012 Butwith@souldreamer'ssyntaxitwoulnotbeposibletowritesome valuesintovariablesandusethemagain. mayuseingthissyntax: @darkfadein(@color,@value){ @foo:darken(@color,@value); return:fadein(@foo); } mayitwouldbepossibleinlaterversionstodosomethinglikethis: @darkfadein(@color,@value){ @foo:darken(@color,@value); for(@i=0;@i<5;@i++):{ @foo:darken(@foo,@i); }; return:fadein(@foo); } Allreactions Sorry,somethingwentwrong. Copylink tylertate commented Mar21,2012 Ihaveasimilarneedtouseafunctionofsomesorttoreturnavalue.Ithinktherearetwopossiblesolutions.Onesolutionwouldbetoextendthevariablesyntaxas@Deltachaosoutlinedabove,whichisessentially: @grid-width(@columns,@column-width){ @computedWidth=@columns*@column-width; return@computedWidth; } div{ width:@grid-width(6,60); } Asecondapproachwouldbetousemixins.SincethecompilertreatsmixinsasJavaScriptfunctionsanyway,addingareturnfeaturetomixinswouldlikelybeasimpleremedy.Here'swhatitwouldlooklike: .grid-width(@columns,@column-width){ @computedWidth=@columns*@column-width; return@computedWidth; } div{ width:.grid-width(6,60); } SASS's"functionaldirectives"provideasimilaroutcome,thoughIbelievethismixinsolutionwouldbemuchmoreelegant. Issues508and609arealsorelatedtothis. 👎 3 TNT-Likely,towry,andruizhang-chowbusreactedwiththumbsdownemoji Allreactions 👎 3reactions Sorry,somethingwentwrong. Copylink Author Deltachaos commented Apr4,2012 Ithinkthesecondsyntaxof@tylertatewouldbethebest.IseamstobetheeasiestbecauseasyousaidlessalreadyparsesmixinsasJavaScript. Wouldsomethinklikethisbepossiblewithmixins? .grid-width(@columns,@column-width){ @computedWidth=@columns*@column-width; for(vari=0;i<=36;i++){ @computedWidth=darken(@computedWidth,i); } return@computedWidth; } div{ width:.grid-width(6,60); } Allreactions Sorry,somethingwentwrong. lukeapage mentionedthisissue Aug12,2012 Createfunctionwithreturnvalue #609 Closed Copylink Member matthew-dean commented Aug14,2012 I'dratherseesomethinglikeadefinedLESSpluginsyntax,andmoveprogramming-likelogictoaJavaScriptLESSplugin.ThesesuggestionsareinconsistentwithcurrentLESSsyntaxanddesign. Allreactions Sorry,somethingwentwrong. Copylink Member lukeapage commented Aug14,2012 Agree..theresabugaboutthatmarkeddocumentationsinceitsrelativelysimpletoaddfunctionswhenyouknowhow. Allreactions Sorry,somethingwentwrong. lukeapage closedthisascompleted Oct18,2012 Copylink jackmoore commented Feb14,2013 Sowhatwastheresolution? Allreactions Sorry,somethingwentwrong. Copylink Member lukeapage commented Feb15,2013 Weneedtodocumentit.seeless/old-lesscss.org#54 andthelinkedissuefromless.jsshowshowyoucanaddafunctiontolessinthebrowser less={functions:{rgbstr:function(color){varstr=color;returnnew(less.tree.Quoted)('"'+str+'"',str,true,1);}}}; atthemomentthereisnowaytopluginfunctionsintothenodeversion,butthereshouldbe Allreactions Sorry,somethingwentwrong. Copylink jackmoore commented Feb15,2013 Thanks,IappreciatetheresponseandthepositiontogetJavaScriptoutofLESS'ssyntax. However,notbeingforcedtoassociateamixin'sreturnvaluewithaspecificpropertyseemslikesuchaclearusecase.Anyonethatusesagridisgoingtowanttodowhat@Deltachaoswastryingtodo.Itwouldbegreattobeabletoachievethiswithoutdroppingdowntothelevelofcreatingaplugin. Allreactions Sorry,somethingwentwrong. Copylink Member lukeapage commented Feb15,2013 Itsatrickything-ifyouneedtohaveloopsorif'sitneedstoliveinaplugin. Howeverifitiscalling3lessfunctionswithspecificvalues,IagreeitmakessensetobeabletoextractthatinsidelessinordertomakethesyntaxDRY-itdoesn'tmakesensetohavetowriteaplugintoextractthefactthatyouwantdarkenby5%intooneplace. Allreactions Sorry,somethingwentwrong. lukeapage reopenedthis Feb15,2013 Copylink Member lukeapage commented Feb15,2013 Ihavere-openedbutthismightbeduplicatedsomewhereelse,we'llsee. atthemomentvariablesfromanmixinsscopeallgetcopiedtotheouterscope-whichiskindofawayforeturningvariables..butitscausinghorribleproblemsandIwanttoremoveit. Allreactions Sorry,somethingwentwrong. Copylink Member lukeapage commented Feb25,2013 duplicateof#538 Allreactions Sorry,somethingwentwrong. lukeapage closedthisascompleted Feb25,2013 Copylink Member matthew-dean commented Feb25,2013 "variablesfromanmixinsscopeallgetcopiedtotheouterscope" Ugh,really?Yes,let'sremovethatbehavior.I'drathervariablesaremarkedforexport,orsomeotherthingthanjustautomaticleaking.That'snotanexpectedbehaviortome.Variablesshouldbeblock-scoped. Allreactions Sorry,somethingwentwrong. Copylink Member lukeapage commented Feb25,2013 yep,itslikesupportingfunctionsviaabackdoorbug Allreactions Sorry,somethingwentwrong. Copylink fabienevain commented Jun14,2013 Ifindahack:ifyoudeclareaglobaljsfunction,youcanuseitlater! @fn:~`fn=function(a) {returna;}`; @arg:8px; p{ font-size:~`fn("@{arg}")`; } 👍 7 avarabei,arminrosu,afc163,micalevisk,xingmolu,brycelund,andhiyangguoreactedwiththumbsupemoji Allreactions 👍 7reactions Sorry,somethingwentwrong. Copylink neoascetic commented Oct10,2013 @fabienevainhavefoundsamehackjustnow:) Allreactions Sorry,somethingwentwrong. Sinetheta mentionedthisissue Feb6,2014 addcolorfunctionstoraise/lowerbrightness #1853 Closed aarontam mentionedthisissue Dec16,2014 User-definedvalueconversionfunction #2341 Closed Copylink ielgnaw commented Oct13,2015 @fabienevainIt'sworkwell,thanks~👍 Allreactions Sorry,somethingwentwrong. slorber mentionedthisissue Dec3,2015 Typesafety:assertfunctiontofailatcompiletime #2747 Closed Copylink Ciantic commented Jan1,2016 Ifoundthatyoucancreateactualfunctionsfromthesameevaljailbyaccessingprocess.mainModule...Onlycatchisthatyoumayhavetoiterateoverprocess.mainModule.childrenandmatchless.jsifthatorderforsomereasonchangesinfuture.Iplannottoiteratejustblindlytrustinglessisthethirdmodule. Unfortunatelyyoucan'taccesstherequire,butyoucanaccessfsandotherwhicharealreadyrequiredbyless,whichisplenty: @anything:`(function(){ //console.log(process.mainModule.children[0].exports);//nodefsishere //console.log(process.mainModule.children[2].children)//childrenofless,morenodemodules! varless=process.mainModule.children[2].exports; less.functions.functionRegistry.add("firstfunc",function(a,context){ //console.log(a,context); returnnewless.tree.Color("00ff00"); }); less.functions.functionRegistry.add("secondfunc",function(a,context){ //console.log(a,context); returnnewless.tree.Color("ff0000"); }); })()`; test{ background:firstfunc(white); color:secondfunc(black); } Neatthingabouthavingrealfunctionisthiscontextvariable,whichcontainsjuicydetailslikethefilebeingprocessedsoyoucane.g.createownsvgdatauriimportwithsettingsetc. EditIwonderwhybackticksareevenintroducedifJSistriedtobekeptout.IlikemyLESSascopy&pasteableaspossiblesopluginsarenotgoodforme. Allreactions Sorry,somethingwentwrong. Copylink Member seven-phases-max commented Jan1,2016 IlikemyLESSascopy&pasteableaspossiblesopluginsarenotgoodforme. Soyouassumeyourcodeis"copy&pasteable"evenifyourequirenode.js-basedless.jscompilerinyourinlinebacktickhacks,butinthesametimefeelitgoeswrongifyouwoulduseplugins?Doh! Allreactions Sorry,somethingwentwrong. Copylink Ciantic commented Jan1,2016 @seven-phases-maxmytoolsareprettymessedup.IfIcouldcontrolthelessccommandlineargumentsIwouldusepluginsprobably.(OrhaveonemasterpluginwhereIstuffeverything)Butno,I'vescrewedmyenvironment,andIhave~100WPthemesinEclipseworkspacewhichIjustcan'tgetridofbecauseallthebuildcommandsetcarestuckinthere. Allreactions Sorry,somethingwentwrong. matthew-dean mentionedthisissue Jan2,2016 Discussion:Variablevisibilityofmixincall/definitionscopeandcallerscopetoeachother #2767 Closed Copylink Member seven-phases-max commented Jan3,2016 @CianticFirstofallyoudon'tneedanyparticularcommandlineoptionstouseacustomfunctionsplugin-ifnecessary(#2479).SecondaryIdoubtwhateverdeeplyscrewedenvironmentprohibitsyoutocontrolcompileroptions(afteralllessc"executable"isjustanOSconsolescriptredirectingtoactualnodescript-soonecaneasilyinjectanythingthereonewayoranother). Eitherwaymycommentwasjustabout"copy&pasteablevs.plugins"adv.whileitturnsouttobejustaworkaroundforabrokenbuildtools/chain. Allreactions Sorry,somethingwentwrong. Copylink Ciantic commented Jan3,2016 @seven-phases-maximportpluginlooksexactlythetoolIneed!ThoughIwouldliketodefinethefunctionsinsidemyproject,notintheglobalregistry,thiswayIcaneditthefunctionswithintheprojectandnotworryaboutbreakingbillionlessfilesifImakeachangetoglobalfunction. Allreactions Sorry,somethingwentwrong. Copylink Contributor rjgotten commented Jan4,2016 @Ciantic ThoughIwouldliketodefinethefunctionsinsidemyproject,notintheglobalregistry,thiswayIcaneditthefunctionswithintheprojectandnotworryaboutbreakingbillionlessfilesifImakeachangetoglobalfunction. Readfurtherin.Theinitialdraftofmypullrequestwenttheeasyrouteofglobalregistration,butwithsomegainedinsightIlaterrefinedittodoscope-localregistration.E.g. .my-mixin(){ @plugin"my-func.js"; @value:my-func(); } willnotleakmy-funcoutsideofthemixinscope.Pathsareofcoursealsorelativetothefilethatcontainsthe@plugindeclaration,soeverythingisneatlybundledandshippableforconsumptionbythird-parties;100%transparantly. Thatwasmydesigngoalforthisfeature.^_^ Allreactions Sorry,somethingwentwrong. Copylink amarkalyane commented Aug17,2016 • edited less.jsisneedforaddingcustomcolorcombiantion problemoccurduringcommitthecode itissupportingbutneedofless.js Allreactions Sorry,somethingwentwrong. Copylink hiyangguo commented Mar24,2019 Ifindahack:ifyoudeclareaglobaljsfunction,youcanuseitlater! @fn:~`fn=function(a) {returna;}`; @arg:8px; p{ font-size:~`fn("@{arg}")`; } @fabienevainHowcanIuselessfunctionsin@fn?Suchashsvsaturation、unitandsoon.Thx. Allreactions Sorry,somethingwentwrong. Copylink Contributor rjgotten commented Mar25,2019 @hiyangguo Youshouldn'tuseinlineJSexpressions,period. Buildandregistercustomfunctionstheappropriateway. Readthedocumentation.It'sallthere:http://lesscss.org/features/#plugin-atrules-feature 👍 3 hiyangguo,MwumLi,anditayganorreactedwiththumbsupemoji Allreactions 👍 3reactions Sorry,somethingwentwrong. Copylink hiyangguo commented Mar28,2019 @rjgottenOK,thankyouverymuch. Allreactions Sorry,somethingwentwrong. Signupforfree tojointhisconversationonGitHub. Alreadyhaveanaccount? Signintocomment Assignees Nooneassigned Labels considerclosing featurerequest lowpriority Projects Noneyet Milestone Nomilestone Development Nobranchesorpullrequests 16participants andothers Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.
延伸文章資訊
- 1less-plugin-functions - npm
Write genuine Less functions in Less itself. ... This experimental "proof-of-concept" plugin exte...
- 2LESS - Functions - Tutorialspoint
LESS - Functions, LESS maps JavaScript code with manipulation of values and uses predefined funct...
- 3用LESS 寫CSS ( 判斷式、迴圈、Function )
function - 單位轉換 · LESS .img2{ width:convert(9s, "ms"); height:convert(14cm, mm); margin:convert(8...
- 4less - C++ Reference - CPlusPlus.com
Binary function object class whose call returns whether the its first argument compares less than...
- 5Functions | Less.js
Less extends CSS with dynamic behavior such as variables, mixins, operations and functions. Less ...