Marketo“跳出”动画标签

时间:2019-01-03 17:46:48

标签: javascript forms label textarea marketo

我正在尝试为Marketo表单创建动画标签。我找到了一个教程,该教程将我带到了最终解决方案的大部分距离,但是,当我们尝试为textarea的“注释”字段设置动画时,它就不足了。

这是代码:

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不会在textarea元素的label元素上呈现新的data属性。新的数据类型属性正在其他标签元素上写入。

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

这是我正在努力的最终结果: https://css-tricks.com/float-labels-css/

This is an example of the label with the data attribute that was rendered by the javascript

1 个答案:

答案 0 :(得分:0)

您需要在原始javascript中进行的所有修改都是将"TEXTAREA" : [undefined]替换为"TEXTAREA" : ["textarea"]。请检查以下示例,其中 Message 是Textarea字段。

原因是JavaScript中labelDesc.fieldEl.nodeName的值将是'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>