我需要帮助,请在这里,我嵌入一个YouTube视频,当用户观看嵌入视频30秒,我想索赔奖励按钮显示,然后剩下的行动是留给livewire这是我已经尝试过,仍然在观看视频30秒后,什么也没有发生
<div class="p-3">
<div class="space-y-3">
<h2 class="font-bold">{{$video->title}}</h2>
<div class="relative rounded-lg overflow-hidden" style="padding-bottom: 56.25%;">
<iframe id="videoFrame" class="absolute top-0 left-0 w-full h-full rounded-lg" src="https://www.youtube.com/embed/{{$video->embed_code}}" frameborder="0" allowfullscreen></iframe>
</div>
<div id="claimButton" style="display: none;">
@if (!$claimed)
<button wire:click="claimReward" class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
Claim Reward
</button>
@else
<div class="mt-2 text-green-500">Reward claimed</div>
@endif
</div>
</div>
</div>
Js
<script>
// Initialize YouTube Player API
var player;
// Function to initialize the player
function onYouTubeIframeAPIReady() {
player = new YT.Player('videoFrame', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
// Function to handle player state change
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
// Video has started playing, start tracking time
startTime = Date.now();
} else if (event.data == YT.PlayerState.ENDED) {
// Video has ended, check if user can claim reward
checkWatchTime();
}
}
// Function to check watch time and show the "Claim Reward" button
function checkWatchTime() {
const currentTime = Date.now();
const elapsedTime = (currentTime - startTime) / 1000; // Convert to seconds
if (elapsedTime >= 30 && !claimed) {
document.getElementById('claimButton').style.display = 'block';
}
}
</script>
<script src="https://www.youtube.com/iframe_api"></script>
我需要帮助
2条答案
按热度按时间fcipmucu1#
您已经对此进行了调试,并测试了stateChanged函数是否被调用,对吗?那么我建议您这样做的方法是设置一个超时,如果用户没有观看30秒,则清除它。
mpgws1up2#
您需要在空div或iframe上初始化YT.player,并在src中设置“enablejsapi”和“origin”。下面是一个基于你的工作片段,使用div:
Here's the documentation