Marketo "Flyout" анимированные ярлыки - PullRequest
0 голосов
/ 03 января 2019

Я пытаюсь создать анимированные ярлыки для формы Marketo.Я нашел учебник, который дает мне большую часть расстояния до окончательного решения, однако он не хватает, когда мы пытаемся анимировать текстовое поле «комментарии».

Вот код:

MktoForms2.whenReady(function(form){
    var formEl = form.getFormElem()[0],
        placeholderableTypes = {
            "INPUT" : ["text", "search", "tel", "url", "email", "password", "number"],
            "TEXTAREA" : [undefined]
        };

    function managePlaceholders(knownTarget){
        var currentValues = form.getValues(),
            fieldNames = knownTarget ? [knownTarget.target.name] : Object.keys(currentValues);

        fieldNames
            .map(function(fieldName){
                var fieldEl = formEl.querySelector("[id='" + fieldName + "']" ),
                labelEl = fieldEl && formEl.querySelector("label[for='" + fieldEl.id + "']" );

                return {
                    fieldEl : fieldEl,
                    labelEl : labelEl,
                    isValued : Boolean(currentValues[fieldName])
                }
            })
            .filter(function(labelDesc){
                return labelDesc.labelEl && 
                    Array.isArray(placeholderableTypes[labelDesc.fieldEl.nodeName]) &&
                        placeholderableTypes[labelDesc.fieldEl.nodeName]
                        .some(function(type){
                            return labelDesc.fieldEl.type == type;
                        });
            })
            .forEach(function(labelDesc){
                labelDesc.labelEl.setAttribute( "data-for-placeholder-hidden", [labelDesc.isValued, knownTarget ? "interactive" : "prefilled"].join("-") );
            });
    }

    formEl.addEventListener("input", managePlaceholders);
    managePlaceholders();
});
.mktoLabel,
.mktoLabel[data-for-placeholder-hidden^="false-"] {
   opacity: 0;
}
.mktoLabel[data-for-placeholder-hidden^="true-"] {
   opacity: 1;
}
.mktoLabel[data-for-placeholder-hidden$="-interactive"] {
   transition: opacity 240ms ease-in;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="//app-ab28.marketo.com/js/forms2/js/forms2.min.js"></script>
<form id="mktoForm_1184"></form>
<script>MktoForms2.loadForm("//app-ab28.marketo.com", "221-SBF-942", 1184);</script>

Вот кодовая ручка для вышеуказанного решения.Но проблема этого решения в том, что оно не обрабатывает текстовую область.В частности, это означает, что JS НЕ рендерит новый атрибут данных в элементе label элемента textarea.Новый атрибут типа данных записывается на других элементах метки.

https://codepen.io/figureone/pen/8ed5444e0558130a5dc3b7029573400f?editors=0010

Это конечный результат, к которому я стремлюсь: https://css -tricks.com / float-label-css /

Это пример метки с атрибутом данных, который был представлен javascript

1 Ответ

0 голосов
/ 04 января 2019

Все, что вам нужно изменить в исходном javascript, это заменить "TEXTAREA" : [undefined] на "TEXTAREA" : ["textarea"].Пожалуйста, проверьте пример ниже, где Сообщение является полем Textarea.

Причина в том, что значение labelDesc.fieldEl.nodeName в javascript будет 'textarea', а не undefined.

MktoForms2.whenReady(function(form){
    var formEl = form.getFormElem()[0],
        placeholderableTypes = {
            "INPUT" : ["text", "search", "tel", "url", "email", "password", "number"],
            "TEXTAREA" : ["textarea"]
        };

    function managePlaceholders(knownTarget){
        var currentValues = form.getValues(),
            fieldNames = knownTarget ? [knownTarget.target.name] : Object.keys(currentValues);

        fieldNames
            .map(function(fieldName){
                var fieldEl = formEl.querySelector("[id='" + fieldName + "']" ),
                labelEl = fieldEl && formEl.querySelector("label[for='" + fieldEl.id + "']" );

                return {
                    fieldEl : fieldEl,
                    labelEl : labelEl,
                    isValued : Boolean(currentValues[fieldName])
                }
            })
            .filter(function(labelDesc){
                return labelDesc.labelEl && 
                    Array.isArray(placeholderableTypes[labelDesc.fieldEl.nodeName]) &&
                        placeholderableTypes[labelDesc.fieldEl.nodeName]
                        .some(function(type){
                            return labelDesc.fieldEl.type == type;
                        });
            })
            .forEach(function(labelDesc){
                labelDesc.labelEl.setAttribute( "data-for-placeholder-hidden", [labelDesc.isValued, knownTarget ? "interactive" : "prefilled"].join("-") );
            });
    }

    formEl.addEventListener("input", managePlaceholders);
    managePlaceholders();
});
.mktoLabel,
.mktoLabel[data-for-placeholder-hidden^="false-"] {
   opacity: 0;
}
.mktoLabel[data-for-placeholder-hidden^="true-"] {
   opacity: 1;
}
.mktoLabel[data-for-placeholder-hidden$="-interactive"] {
   transition: opacity 240ms ease-in;
}
<form id="mktoForm_1184" class="mktoForm"></form>

<script id="mktoForms2Lib" src="//app-ab28.marketo.com/js/forms2/js/forms2.min.js"></script>

<!-- Form Mockup -->
<script>
var storedFormDescriptors = {
  "221-SBF-942" : {
    "1184" : {"Id":1184,"Vid":1184,"Status":"approved","Name":"Contact Us.Website Footer - Contact Us Form","Description":"","Layout":"above","GutterWidth":10,"OffsetWidth":10,"HasTwoButtons":true,"SubmitLabel":"Submit","ResetLabel":"Clear","ButtonLocation":"120","LabelWidth":100,"FieldWidth":150,"ToolTipType":"none","FontFamily":"Helvetica, Arial, sans-serif","FontSize":"13px","FontColor":"#333","FontUrl":null,"LineMargin":10,"ProcessorVersion":2,"CreatedByUserid":3485,"ProcessOptions":{"language":"English","locale":"en_US","profiling":{"isEnabled":false,"numberOfProfilingFields":3,"alwaysShowFields":[]},"socialSignOn":{"isEnabled":false,"enabledNetworks":[],"cfId":null,"codeSnippet":null},"knownLead":{"type":"form","template":""}},"EnableDeferredMode":0,"ButtonType":null,"ButtonImageUrl":null,"ButtonText":null,"ButtonSubmissionText":"Please Wait","ButtonStyle":{"id":11,"className":"mktoSimple","css":".mktoForm .mktoButtonWrap.mktoSimple .mktoButton {\ncolor:#fff;\nborder:1px solid #75ae4c;\npadding:0.4em 1em;\nfont-size:1em;\nbackground-color:#99c47c;\nbackground-image: -webkit-gradient(linear, left top, left bottom, from(#99c47c), to(#75ae4c));\nbackground-image: -webkit-linear-gradient(top, #99c47c, #75ae4c);\nbackground-image: -moz-linear-gradient(top, #99c47c, #75ae4c);\nbackground-image: linear-gradient(to bottom, #99c47c, #75ae4c);\n}\n.mktoForm .mktoButtonWrap.mktoSimple .mktoButton:hover {\nborder:1px solid #447f19;\n}\n.mktoForm .mktoButtonWrap.mktoSimple .mktoButton:focus {\noutline:none;\nborder:1px solid #447f19;\n}\n.mktoForm .mktoButtonWrap.mktoSimple .mktoButton:active{\nbackground-color:#75ae4c;\nbackground-image: -webkit-gradient(linear, left top, left bottom, from(#75ae4c), to(#99c47c));\nbackground-image: -webkit-linear-gradient(top, #75ae4c, #99c47c);\nbackground-image: -moz-linear-gradient(top, #75ae4c, #99c47c);\nbackground-image: linear-gradient(to bottom, #75ae4c, #99c47c);\n}\n","buttonColor":null},"ThemeStyle":{"id":2,"displayOrder":1,"name":"Simple","backgroundColor":"#FFF","layout":"left","fontFamily":"Helvetica, Arial, sans-serif","fontSize":"13px","fontColor":"#333","offsetWidth":10,"gutterWidth":10,"labelWidth":100,"fieldWidth":150,"lineMargin":10,"useBackgroundColorOnPreview":false,"css":".mktoForm fieldset.mkt3-formEditorFieldContainer{border: solid 1px gray;}.mktoForm fieldset.mkt3-formEditorFieldContainer legend{padding:0 1em;}","href":"css\/forms2-theme-simple.css","buttonStyleId":11},"ThemeStyleOverride":"\/* Add your custom CSS below *\/\n\n@import url('https:\/\/fonts.googleapis.com\/css?family=Roboto:400,500');\n\n.mktoForm {\n  width:100% !important;\n  background-color:#32364d !important;\n}\n\n.mktoFormRow, .mktoFieldWrap, .mktoButtonRow {\n  width:100%;\n}\n\n.mktoForm input[type=url], \n.mktoForm input[type=text], \n.mktoForm input[type=date], \n.mktoForm input[type=tel], \n.mktoForm input[type=email], \n.mktoForm input[type=number], \n.mktoForm textarea.mktoField, \n.mktoForm select.mktoField {\n    width:100% !important;\n\tpadding-bottom:12px !important;\n    padding-top:8px !important;\n    padding-left:0px !important;\n    border-top: none !important;\n    border-left: none !important;\n    border-right: none !important;\n  \tborder-bottom: 3px solid #656979 !important;\n  \tfont-family: 'Roboto', sans-serif !important;\n    font-weight:500 !important;\n  \tcolor: #ffffff;\n    font-size: 28px !important;\n    background-color: transparent !important;\n    outline: none !important;\n    border-radius: 0 !important;\n}\n\n.mktoForm .mktoRequiredField label.mktoLabel {\n    font-weight:normal !important;\n}\n\n.mktoFormCol {\n  width:25%;\n}\n\n.mktoFieldWrap {\n  padding-right:16px !important;\n  box-sizing: border-box;\n}\n.mktoFormCol:nth-child(4) .mktoFieldWrap {\n  padding-right:0 !important;\n}\n\n.mktoButtonRow {\n  text-align:left !important;\n}\n.mktoButtonWrap {\n  margin-left:0 !important;\n}\n\n.mktoForm .mktoOffset {\n    float: left;\n    height:0 !important;\n    width:10px;\n}\n\n\/* Hint Text Styling *\/\n\n::-webkit-input-placeholder {\n  color: #aba9a9;\n}\n::-moz-placeholder { \n  color: #aba9a9;\n}\n:-ms-input-placeholder {\n  color: #aba9a9;\n}\n:-moz-placeholder {\n  color: #aba9a9;\n}\n\n\/* Button Styling *\/\n\n.mktoForm .mktoButtonWrap.mktoSimple .mktoButton {\n  background:#FF665E !important;\n  border:0 !important;\n  font-size:14px !important;\n  padding:10px 40px !important;\n  border-radius:25px !important;\n  font-weight: bold !important;\n  margin-top:15px !important;\n}\n\n\n@media only screen and (max-width: 800px) {\n  .mktoFormCol {\n    width:50% !important;\n  }\n  .mktoFieldWrap {\n  padding-right:16px !important;\n  box-sizing: border-box;\n}\n.mktoFormCol:nth-child(even) .mktoFieldWrap {\n  padding-right:0 !important;\n}\n}\n\n@media only screen and (max-width: 480px) {\n  .mktoFormCol {\n    width:100% !important;\n  }\n  .mktoFieldWrap {\n    padding-right:0 !important;\n  }\n}\n\n\/* Label Styling *\/\n\n.mktoLabel {\n  font-family: 'Roboto', sans-serif;\n  color: #FF665E\n}\n.mktoAsterix {\n         display:none !important;\n}\n","rows":[[{"Id":7707,"Name":"FirstName","Datatype":"string","Maxlength":255,"InputLabel":"First","InputInitialValue":"","InputSourceChannel":"constant","LabelWidth":147,"PlaceholderText":"First","ValidationMessage":"This field is required."},{"Id":7708,"Name":"LastName","Datatype":"string","Maxlength":255,"InputLabel":"Last","InputInitialValue":"","InputSourceChannel":"constant","LabelWidth":194,"PlaceholderText":"Last","ValidationMessage":"This field is required."},{"Id":7709,"Name":"Email","Datatype":"email","Maxlength":255,"InputLabel":"Email","InputInitialValue":"","InputSourceChannel":"constant","LabelWidth":179,"PlaceholderText":"Email","ValidationMessage":"Must be valid email. \u003Cspan class='mktoErrorDetail'\u003Eexample@yourdomain.com\u003C\/span\u003E"},{"Id":7710,"Name":"Company","Datatype":"string","Maxlength":255,"InputLabel":"Company","InputInitialValue":"","InputSourceChannel":"constant","LabelWidth":218,"ProfilingFieldNumber":0,"PlaceholderText":"Company","ValidationMessage":"This field is required."}],[{"Id":5247,"Name":"Message","Datatype":"textarea","Maxlength":32000,"InputLabel":"Message","PlaceholderText":"Message","InputInitialValue":"","InputSourceChannel":"constant","VisibleRows":2,"ProfilingFieldNumber":0,"ValidationMessage":"This field is required."}]],"fieldsetRows":[],"action":null,"munchkinId":"221-SBF-942"}
  }
};

MktoForms2.setOptions({baseUrl:"https://app-ab28.marketo.com/js/forms2/"});
MktoForms2.newForm(storedFormDescriptors["221-SBF-942"]["1184"],function(form){ 
    form.render();
});
</script>
...