【问题标题】:Javascript code with eventListener does't work for a video button-control-system带有 eventListener 的 Javascript 代码不适用于视频按钮控制系统
【发布时间】:2017-02-23 17:03:17
【问题描述】:

有人给我发了一个代码,我试着运行它。问题是 Javascript 文件无法正常工作。结果必须是我的视频的按钮控制系统。我希望有人可以看看它。

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>dfdfs</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script type="text/javascript" src="main.js"></script>
</head>
<body>

<!-- Simplified the markup a little, less is more -->
<div id="p1">
  <a href="#/" id='b1' class='play'> </a>
  <video id="v1">
            <source src="http://html5demos.com/assets/dizzy.mp4" type="video/mp4">
   </video>
</div>

</body>
</html>

CSS:

/* This container wraps neatly around 
|| the video's width
*/

#p1 {
  position: relative;
  display: table-cell;

}


/* This is to make the button an overlay */

#b1 {
  font-size: 100px;
  color: rgba(0, 255, 255, .3);
  position: absolute;
  z-index: 1;
  height: 100px;
  width: 100px;
  top: calc(50% - 50px);
  left: calc(50% - 50px);
  text-decoration: none;
}


/* These two rulsets use  simple HTML entities
|| for play/pause buttons
*/

.play::after {
  content: '\25b6';
}

.pause::after {
  content: '\23f8';
}

JAVASCRIPT:

// Reference button and container
var btn1 = document.getElementById('b1');
var pyr1 = document.getElementById('p1');

// When button is clicked...
btn1.addEventListener('click', function(event) {

  // Reference video
  var vid1 = document.getElementById('v1');

  // Conditions based on state: paused
  if (vid1.paused) {
    vid1.play();
  } else {
    vid1.pause();
  }
  /* Whatever the new state is doesn't matter if...
  || we have either .play or .pause class on button
  || previously and that both classes will toggle
  || at the same time.
  */
  btn1.classList.toggle('play');
  btn1.classList.toggle('pause');
}, false);

// If the mouse leaves the area of container...
pyr1.addEventListener('mouseout', function(event) {

  // If the button has the class .pause...
  if (btn1.classList.contains('pause')) {

    // set it's opacity to 0
    btn1.style.opacity = 0;

    // and make it fade away
    btn1.style.transition = '1s ease';
  }
}, false);

// If the mouse enters the container's area...
pyr1.addEventListener('mouseover', function(event) {

  // if the button has the class .pause...
  if (btn1.classList.contains('pause')) {

    // set it's opacity to 1  
    btn1.style.opacity = 1;

    // and make it fade in
    btn1.style.transition = '1s ease';
  }
}, false);

【问题讨论】:

  • 究竟是什么不工作?
  • 脚本在 DOM 准备好之前执行。将&lt;script&gt; 标记移到页面底部,就在&lt;/body&gt; 标记之前

标签: javascript html button toggle event-listener


【解决方案1】:

您上传的代码可以正常工作 (jsfiddle)。

正如 Andreas 所说,移动你的脚本标签 &lt;script type="text/javascript" src="main.js"&gt;&lt;/script&gt; 到您的 html 文件的末尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多