如何使用javascript将内容与HTML5视频同步?

时间:2018-12-12 00:05:22

标签: javascript jquery html5 validation html5-video

我有一个包含一些输入字段名称,电子邮件等的表格,我有一个视频(我无法在此处张贴),其中包含一个女孩在说,例如,电子邮件错误,请输入新的电子邮件,密码不正确输入正确的密码,使用名字,请输入新名称,等等,

所以我想当用户输入名称而不是显示的消息(例如好名)时,我想播放一段视频,说“哦,这是好名”,反之亦然,

这是jsfiddle供参考: validation message using video

这是我到目前为止所拥有的

<!--PEN CODE-->
<div id="contactForm" class="contactForm">
    <div id="formHeader" class="formHeader">
        <h1 id="message">Contact Me</h1>
    </div>
    <div id="formBody" class="formBody">
        <form action="" method="POST" name="contactForm">
            <div class="inputContainer">
                <label for="userName">
                    <i class="fa fa-lg fa-fw fa-user"></i>
                </label>
                <input name="name" id="userName" type="text" placeholder="John Smith">
            </div>
            <div class="inputContainer">
                <label for="userEmail">
                    <i class="fa fa-lg fa-fw fa-envelope"></i>
                </label>
                <input name="email" id="userEmail" type="email" placeholder="jsmith@domain.com">
            </div>
            <div class="inputContainer">
                <textarea name="feedback" id="userMessage" rows="10" placeholder="Enter your message"></textarea>
            </div>
            <input id="submitBtn" class="submitBtn" type="submit" value="Send">
        </form>
    </div>
</div>
<center><p><em>NOTE: This form is for presentation only. Any form data entered is not submitted</em></p></center>
<!--END PEN CODE-->


    <div class="video=wrapper">

      <video id="video1" width="420">
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  </video>


    </div>

这是我到目前为止拥有的

(function() {
    "use strict";
    var //GLOBAL VARIABLES
    input,
            container,
            //CSS CLASSES
            classSuccess = "success",
            classError = "error",
            //FORM VALIDATOR
            formValidator = {
                init: function() {
                    this.cacheDom();
                    this.bindEvents();
                },
                cacheDom: function() {
                    //MAIN PARENT ELEMENT
                    this.contactForm = document.getElementById("contactForm");
                    //MAIN FORM ELEMENTS
                    this.formHeader = document.querySelector("#formHeader h1");
                    this.formBody = document.getElementById("formBody");
                    this.inputContainer = document.getElementsByClassName("inputContainer");
                    //USER INPUT ELEMENTS
                    //INPUT FIELDS
                    this.fields = {
                        userName: document.getElementById("userName"),
                        userEmail: document.getElementById("userEmail"),
                        userMessage: document.getElementById("userMessage")
                    };
                    this.submitBtn = document.getElementById("submitBtn");
                },
                bindEvents: function() {
                    var i;
                    //RUN RULES ON SUBMIT BUTTON CLICK
                    this.submitBtn.onclick = this.runRules.bind(this);
                    //BIND EVENTS TO EACH INPUT FIELD
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            //VARIABLES
                            input = this.fields[i];
                            container = input.parentElement;
                            //RUN RULES WHEN INPUT HAS FOCUS
                            input.onfocus = this.runRules.bind(this);
                            //RESET ERRORS WHEN CONTAINER IS CLICKED
                            container.onclick = this.resetErrors.bind(this, input);
                        }
                    }
                },
                runRules: function(evnt) {
                    var target = evnt.target,
                            type = evnt.type;
                    //IF EVENT ON SUBMIT BUTTON
                    if (target === this.submitBtn) {
                        //PREVENT FORM SUBMITTION
                        this.preventDefault(evnt);
                        //IF INPUT HAS FOCUS
                    } else if (type === "focus") {
                        //RESET CLASSLIST
                        this.resetClassList(target.parentElement);
                        //RESET ERRORS
                        this.resetErrors(target);
                        return false;
                    }
                    //RESET CLASSLIST
                    this.resetClassList();
                    //CHECK FIELDS
                    this.checkFields();
                },
                preventDefault: function(evnt) {
                    //PREVENT DEFUALT
                    evnt.preventDefault();
                },
                checkFields: function() {
                    var i,
                            validCount = 0,
                            //EMAIL FILTER
                            filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                    //CYLCE THROUGH INPUTS
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            input = this.fields[i];
                            //CHECK IF FIELD IS EMPTY
                            if (input.value === "") {
                                //ADD ERROR CLASS
                                this.addClass(input, classError);
                                //CHECK IF EMAIL IS VALID
                            } else if (i === "userEmail" && !filter.test(input.value)) {
                                //ADD ERROR CLASS
                                this.addClass(input, classError);
                            } else {
                                //FIELD IS VALID
                                this.addClass(input, classSuccess);
                                validCount += 1;
                            }
                        }
                    }
                    //IF ALL FEILDS ARE VALID
                    if (validCount === 3) {
                        //SUBMIT FORM
                        this.submitForm();
                    }
                },
                addClass: function(input, clss) {
                    container = input.parentElement;
                    //IF INPUT HAS ERROR
                    if (clss === classError) {
                        //SHOW ERROR MESSAGE
                        this.errorMessage(input);
                    }
                    //ADD CLASS
                    input.parentElement.classList.add(clss);
                },
                errorMessage: function(input) {
                    var message;
                    //IF USERNAME HAS ERROR
                    if (input === this.fields.userName) {
                  //grab data from video and interact it with html5 form
                  var videoElement = document.getElementById('video1')[0];
                  videoElement.addEventListener('loadmetadata', function(){
                  this.currentTime =20;
                }, false)

                        //ELSE IF USEREMAIL HAS ERROR
                    } else if (input === this.fields.userEmail) {
            //grab data from video and interact it with html5 form
            var videoElement = document.getElementById('video1')[0];
            videoElement.addEventListener('loadmetadata', function(){
            this.currentTime =70;
          }, false)
                        //ELSE IF USERMESSAGE HAS ERROR
                    } else if (input === this.fields.userMessage) {
            //grab data from video and interact it with html5 form
            var videoElement = document.getElementById('video1')[0];
            videoElement.addEventListener('loadmetadata', function(){
            this.currentTime =50;
          }, false)
                    }
                    this.renderError(input, message);
                },
                renderError: function(input, message) {
                    var html;
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //RENDER HTML
                    html = document.createElement("div");
                    html.setAttribute("class", "message");
                    html.innerHTML = message;
                    //IF MESSAGE ELEMENT DOESN'T EXIST
                    if (!container.getElementsByClassName("message")[0]) {
                        //INSERT MESSAGE TO INPUT CONTAINER
                        container.insertBefore(html, container.firstElementChild);
                    }
                },
                resetClassList: function(input) {
                    var i;
                    //IF TARGETING SPECIFIC INPUT
                    if (input) {
                        //GET INPUT CONTAINER
                        container = input.parentElement;
                        //REMOVE CLASSES
                        container.classList.remove(classError, classSuccess);
                        //FOCUS ON INPUT FIELD
                        input.focus();
                    } else {
                        for (i in this.fields) {
                            if (this.fields.hasOwnProperty(i)) {
                                //REMOVE CLASSES FROM ALL FIELDS
                                this.fields[i].parentElement.classList.remove(classError, classSuccess);
                            }
                        }
                    }
                },
                resetErrors: function(input) {
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //IF CONTAINER CONTAINS ERROR
                    if (container.classList.contains(classError)) {
                        //RESET CLASSES
                        this.resetClassList(input);
                    }
                },
                submitForm: function() {
                    var waitForAnimation;
                    //ADD SUCCESS CLASS
                    this.contactForm.classList.add(classSuccess);
                    //WAIT FOR ANIMATION TO FINISH
                    this.changeHeader("Sent Succesfully");
                    //WAIT FOR ANIMATION TO FINISH
                    setTimeout(this.changeHeader.bind(this, "Thank you for your feedback"), 1200);
                },
                changeHeader: function(text) {
                    //CHANGE HEADER TEXT
                    this.formHeader.innerHTML = text;
                }
            };


    //INITIATE FORM VALIDATOR
    formValidator.init();


}());

**

  

注意:您可以使用任何视频,重要的是有效的解决方案

**

不幸的是,这无法正常工作

我的代码在做什么错了?

1 个答案:

答案 0 :(得分:1)

首先,您似乎正在将jQuery代码与本机JS混合在一起。您没有通过以下方式选择视频元素:

document.getElementById("video1")[0];

这需要这样做:

document.getElementById("video1");

接下来,您可以在可能触发或永远不会触发的元素上设置事件侦听器。让我们确保可以通过强制视频提取来触发事件处理程序。

您的样本中有很多事情要做,所以我将其分解为最小的部分。

  1. 该按钮模拟错误的表单字段。
  2. 接下来,加载视频,以便触发canplay事件。
  3. 然后单击按钮并设置视频URL以强制加载视频
  4. 最后,使用Async / Await并播放视频。
    • 注意:如果用户代理阻止播放视频,则该视频可能无法播放

let vidElement = document.getElementById('video1');
vidElement.addEventListener('canplay', playVideo);

document.querySelector('button').addEventListener('click', loadvideo);

function loadvideo() {
  vidElement.src = "https://www.w3schools.com/html/mov_bbb.mp4";
}

async function playVideo() {
  vidElement.currentTime = 70;
  console.log("Playing video from: ", vidElement.currentTime);
  await vidElement.play().catch(e => console.log("error: ", e.message));
}
<button>Make Form Error</button>
<br>
<video id="video1" width="420">
    <source type="video/mp4">
  </video>