如何在输入范围内获得悬停时间的值

时间:2015-05-27 04:26:34

标签: javascript jquery

我的问题可能有点模糊,所以在这里详细解释它。我试图在页面上开发一个简单的视频播放器。我使用输入范围来显示文件持续时间和当前时间,就像任何标准播放器一样。这是我的剧本。

<script>
        var vid, playbtn, seekslider, curtimeText, durtimeText, mutebtn, volumeslider, fullscreenbtn;
        function initializePlayer() {

            //creating global object
            vid = document.getElementById('my_video');
            playbtn = document.getElementById('playpausebtn');
            seekslider = document.getElementById('seekslider');
            curtimeText = document.getElementById('curtimeText');
            durtimeText = document.getElementById('durtimeText');
            mutebtn = document.getElementById('mutebtn');
            volumeslider = document.getElementById('volumeslider');
            fullscreenbtn = document.getElementById('fullscreenbtn');

            //creating event for objects
            playbtn.addEventListener("click", playPause, false);
            seekslider.addEventListener("change", vidSeek, false);
            vid.addEventListener("timeupdate", seektimeupdate, false);
            mutebtn.addEventListener("click", vidmute, false);
            volumeslider.addEventListener("change", setvolume, false);
            fullscreenbtn.addEventListener("click", toggleFullScreen, false);
        }

        window.onload = initializePlayer;

        function playPause() {
            if (vid.paused) {
                vid.play();
                playbtn.innerHTML = "Pause";
            } else {
                vid.pause();
                playbtn.innerHTML = "Play";
            }

        }
        function vidSeek() {
            var seekto = vid.duration * (seekslider.value / 100);
            vid.currentTime = seekto;
        }
        function seektimeupdate() {
            var nt = vid.currentTime * (100 / vid.duration);
            seekslider.value = nt;
            var curmins = Math.floor(vid.currentTime / 60);
            var cursecs = Math.floor(vid.currentTime - curmins * 60);
            var durmins = Math.floor(vid.duration / 60);
            var dursecs = Math.floor(vid.duration - durmins * 60);
            if (cursecs < 10) {
                cursecs = "0" + cursecs;
            }
            if (dursecs < 10) {
                dursecs = "0" + dursecs;
            }
            if (curmins < 10) {
                curmins = "0" + curmins;
            }
            if (durmins < 10) {
                durmins = "0" + durmins;
            }
            curtimeText.innerHTML = curmins + ":" + cursecs;
            durtimeText.innerHTML = durmins + ":" + dursecs;
        }
        function vidmute() {

            if (vid.muted) {
                vid.muted = false;
                mutebtn.innerHTML = "Mute";
            } else {
                vid.muted = true;
                mutebtn.innerHTML = "Unmute";
            }
        }
        function setvolume() {
            vid.volume = volumeslider.value / 100;
        }
        function toggleFullScreen() {
            if (vid.requestFullScreen) {
                vid.requestFullScreen();
            } else if (vid.webkitRequestFullScreen) {
                vid.webkitRequestFullScreen();
            } else if (vid.mozRequestFullScreen) {
                vid.mozRequestFullScreen();
            }
        }
</script>

和我的HTML代码:

<div id="Video_player_box">
    <video id="my_video">
        <source src="Videos/cowhand.mp4" type="video/mp4">
        <!-- Your browser does not support HTML5 video.-->
    </video>
    <div id="Video_controls_bar">
        <button id="playpausebtn">Play</button>             
        <span id="curtimeText"></span>
        <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1"> 
        <span id="durtimeText"></span>
        <button id="mutebtn">Mute</button>
        <input id="volumeslider" type="range" min="0" max="100" value="50" step="1">
        <button id="fullscreenbtn">[&nbsp;&nbsp;]</button>
    </div> 
</div>

现在我要做的是在小工具提示上显示用户指向seeklider的时间。就好像视频长10分钟,并且用户指向范围栏(seeklider)的中间我想要一个小工具提示来显示用户指向即5:01但我真的不知道如何编码!我很感激有关如何实现这个功能的任何帮助。

4 个答案:

答案 0 :(得分:3)

借鉴Jesse's answer以及this page以及我自己的一些实验,我更进了一步,想出了让工具提示跟随鼠标的代码。

I created a Codepen代码,Ali,并添加了一个处理工具提示的函数。您可以在那里查看完整代码,但这是我在原始代码中添加的内容:

HTML 中,我将seekslider包装在一个容器中,并添加了工具提示的范围,如下所示:

<div id="seek-container">
    <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1" /><span id="seek-tooltip"></span>
</div>

然后,使用 CSS ,我:

  • 确保seek-container保持内联,就像滑块一样。
  • seek-tooltip位置设置为绝对位置,或相对于文档(您稍后会看到原因),将其设置为最初不可见,并为其提供一个漂亮的阴影。
  • seek-tooltip悬停在seek-container上时,#seek-container { display: inline; } #seek-tooltip { position: absolute; display: none; box-shadow: 5px 5px 8px #CCC; } #seek-container:hover #seek-tooltip { display: inline; background: #fff; } 变为可见的白色背景。

这是完成所有这些的代码:

tooltip

最后,好东西: JavaScript 。现在,尽管你标记了这个问题jQuery,我注意到你的原始代码并没有包含任何内容,所以我选择了你的诉讼而不是在这个答案中使用jQuery。它当然可行(可能更容易一些),但我希望这一点尽可能与你已经拥有的一致。

无论如何,这就是我所做的:

  • 在开头添加了另一个变量:seek-tooltip
  • tooltip元素存储到mousemove变量
  • seekslider添加了一个sliderTooltip事件监听器,该监听器调用了函数sliderTooltip
  • 编写了计算当前悬停时间的函数offsetTop(感谢Jesse),将工具提示的内容设置为时间,将工具提示的顶部位置设置为滑块的顶部位置,然后设置工具提示的左侧位置与鼠标的位置相同。这就是工具提示的位置设置为绝对的原因:我使用滑块的pageX属性确定必要的y坐标和var tooltip; //This would be at the beginning with your other definitions //--The stuff below would be inside your window.onload function-- //Populate your tooltip variable tooltip = document.getElementById("seek-tooltip"); //Bind the tooltip update function to the slider's mousemove event seekslider.addEventListener("mousemove", sliderTooltip, false); //--Done with the stuff in your window.onload-- function sliderTooltip(e) { //The parameter e is the mousemove event that was fired //First, calculate the current hovered time (thanks Jesse) var hoverTime = ((e.clientX - e.target.offsetLeft) / e.target.clientWidth * parseFloat(e.target.getAttribute('max'))).toFixed(2); var hoverMins = Math.floor(hoverTime / 60); var hoverSecs = Math.floor(hoverTime - hoverMins * 60); //Now that we've got the time, simply populate the tooltip! tooltip.innerHTML = hoverMins + ":" + hoverSecs; //Set the "top" CSS to the top position of the slider tooltip.style.top = seekslider.offsetTop + "px"; //Set the "left" CSS to our mouse position, plus 10 pixels //to offset it a bit to allow the user to click on the slider and not on the tooltip tooltip.style.left = (e.pageX + 10) + "px"; 属性来抓取鼠标& #x; x坐标,两者都是相对于文档的;使工具提示绝对确保工具提示和鼠标使用相同的坐标。

以下是代码:

05-26 12:07:19.613: E/AndroidRuntime(18953): java.lang.Error: Unresolved compilation problem: 
05-26 12:07:19.613: E/AndroidRuntime(18953):    The import android.support.v7 cannot be resolved
05-26 12:07:19.613: E/AndroidRuntime(18953):    at com.sim.clientkeeper.MainActivity.<init>(MainActivity.java:7)
05-26 12:07:19.613: E/AndroidRuntime(18953):    at java.lang.Class.newInstanceImpl(Native Method)



`import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    SQLiteDatabase sqlDba;
    SQLiteAdapter DbAdapter;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        DbAdapter = new SQLiteAdapter(getApplicationContext());
          DbAdapter.open();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onClickClient(View v)
    {
        Intent i=new Intent(this,CLient_List_Activity.class);
        startActivity(i);
    }

    public void onClickTravel(View v)
    {
        Intent i=new Intent(this,Travel_Activity.class);
        startActivity(i);
    }

    }
`

}     }

如果您对jQuery版本的外观感到好奇,那么除了选择工具提示并添加其事件监听器的方式外,它几乎完全相同。

答案 1 :(得分:2)

这是一个简单的功能,可以帮助你。它使用事件数据获取所有必需的数字,并根据滑块的max属性返回一个值。

&#13;
&#13;
function calcSliderPos(e) {
  return ( e.clientX - e.target.offsetLeft ) / e.target.clientWidth * parseFloat(e.target.getAttribute('max'));
}

//attach to slider and fire on mousemove
document.getElementById('seekslider').addEventListener('mousemove', function(e) {
  //inject the value into the durtime span
  document.getElementById('durtimeText').innerHTML = calcSliderPos(e).toFixed(2);
});
&#13;
<input id="seekslider" type="range" min="0" max="100" value="0" step="0.1"> 
<span id="durtimeText"></span>
        
&#13;
&#13;
&#13;

请注意,这只会为您提供估计的排名。我认为真正获得100%准确位置的唯一方法是在滑块上选择一个点并获取该值。

答案 2 :(得分:1)

我已经尝试了 jming的回答,但对我来说,提供了完全错误的价值。经过如下修改后,我的问题就解决了。

var hoverTime = (e.offsetX / e.target.clientWidth) * parseInt(e.target.getAttribute('max'),10);

这提供了更准确的滑块内部时间值。

感谢jming他出色的工作。

答案 3 :(得分:1)

您好我正在处理当前Time项目的这个工具提示,我得到了一个我自己编写的脚本实际上非常棒,它是我在这个项目中看到的每个代码的混合

&#13;
&#13;
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

    Log.d(VIEW_LOG_TAG,"Start: "+start+" Length before: "+lengthBefore+" Length After: "+lengthAfter+" TextLength: "+text.length());
    Spannable str = this.getText();
    CharacterStyle ss;
    UnderlineSpan ss1=null;
    int endLength = text.toString().length();

    switch (currentTypeface) {
        case TYPEFACE_NORMAL:
            ss = new StyleSpan(Typeface.NORMAL);
            break;
        case TYPEFACE_BOLD:
            ss = new StyleSpan(Typeface.BOLD);
            break;
        case TYPEFACE_ITALICS:
            ss = new StyleSpan(Typeface.ITALIC);
            break;
        case TYPEFACE_BOLD_ITALICS:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            break;
        case TYPEFACE_UNDERLINE:
            ss= new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.ITALIC);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            ss1=new UnderlineSpan();
            break;
        default:
            ss = new StyleSpan(Typeface.NORMAL);
    }
        if(lastCursorPosition>endLength)
            return;
        Log.d(TextArea.class.getSimpleName(), new Integer(lastCursorPosition).toString() + new Integer(endLength).toString());
    if(ss1!=null)
        str.setSpan(ss1, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str.setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
&#13;
 var video = $('video')[0];
 $('input').mousemove(function(e){
        var progress = $("input");
        var maxduration = video.duration;
        var position = e.pageX - progress.offset().left;
        var tooltip = $("span")[0];
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        var min = Math.floor((percentage / 100 * video.duration) / 60);
        var sec = Math.floor((percentage / 100 * video.duration) - min * 60); 
        if(min < 10){
            min = "0" + min;
        }
        if(sec < 10){
            sec = "0" + sec;
        }
        $("span").html(min + ":" + sec); 
  //You can use this code below to align your tooltip when you have completed styling it
  /*tooltip.style.top = -progress[0].offsetTop+(-10) + "px";
         console.log(progress.offset().top);
         tooltip.style.marginLeft = (e.pageX - 25) + "px";
  //Note: You may have to edit this code according to your styling
*/
});
//Just for testing
var timeDrag = false;
$('input').on('mousedown', function(e) {
        timeDrag = true;
        video.pause();
        updatebar(e.pageX);
 });
   var updatebar = function(x) {
        var progress = $('input');

        //calculate drag position
        //and update video currenttime
        //as well as progress bar
        var maxduration = video.duration;
        var position = x - progress.offset().left;
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        video.currentTime = maxduration * percentage / 100;
    };
 
&#13;
input{
  width:400px; /*Just for demonstration that this code does not depend on width of the slider*/
}
&#13;
&#13;
&#13;

这一切都将起作用,谢谢