最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how to make my video play when hover on it with pure javascript - Stack Overflow

programmeradmin0浏览0评论

i try to do this with many different way but i didn't get the result i want so can anyone help

<div style="width:500px;height:500px;">
    <video controls autoplay width="400" height="400">
        <source src="video/2.mp4" type="video/mp4">
    </video>    
</div>

and here is the only answer i found when i search but i dont understand it well and there is jquery on it i want to make it pure javascript

var figure = $(".video");
var vid = figure.find("video");

[].forEach.call(figure, function (item,index) {
item.addEventListener('mouseover', hoverVideo.bind(item,index), false);
item.addEventListener('mouseout', hideVideo.bind(item,index), false);
});

function hoverVideo(index, e) {
vid[index].play(); 
}

function hideVideo(index, e) {
vid[index].pause(); 
}

i try to do this with many different way but i didn't get the result i want so can anyone help

<div style="width:500px;height:500px;">
    <video controls autoplay width="400" height="400">
        <source src="video/2.mp4" type="video/mp4">
    </video>    
</div>

and here is the only answer i found when i search but i dont understand it well and there is jquery on it i want to make it pure javascript

var figure = $(".video");
var vid = figure.find("video");

[].forEach.call(figure, function (item,index) {
item.addEventListener('mouseover', hoverVideo.bind(item,index), false);
item.addEventListener('mouseout', hideVideo.bind(item,index), false);
});

function hoverVideo(index, e) {
vid[index].play(); 
}

function hideVideo(index, e) {
vid[index].pause(); 
}
Share Improve this question asked Jul 19, 2018 at 21:38 Mohamed Nageh OtafyMohamed Nageh Otafy 191 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The answer is pretty simple:

document.getElementById("myVid").addEventListener("mouseover", function() {
	this.play();
});

document.getElementById("myVid").addEventListener("mouseleave", function() {
	this.pause();
});
<div style="width:500px;height:500px;">
    <video id="myVid" controls autoplay width="400" height="400">
        <source src="https://www.w3schools./tags/mov_bbb.mp4" type="video/mp4">
    </video>    
</div>

This should work for you. You can find more information here about HTML5 video API.

const videoPlayer = document.querySelector('.videoplayer');

videoPlayer.addEventListener('mouseover', () => {
    videoPlayer.play();
});
<p>Hover canvas to play the video</p>
<video class="videoplayer" width="320" height="240">
  <source src="https://www.sample-videos./video/mp4/720/big_buck_bunny_720p_1mb.mp4" type="video/mp4">
</video>

发布评论

评论列表(0)

  1. 暂无评论