1

我为视频播放器创建了一个自定义音量栏。一切正常,但我试图在拖动控件时反转音量变化的方向。我认为这与以下事实有关:当我计算位置并将其转换为百分比时,我的控制 div 的顶部是 0%,底部是 100%。位置和百分比计算如下:

var position = y - volume.offset().top;
percentage = 100 * position / volume.height();

如果点击控制div的底部,console.log(position); 读出 100%。我希望它读出 0%,所以当点击底部时,音量会下降,当点击顶部时,音量会上升(到 100%)。

这是代码

HTML

<video id="video">
... video sources
</video>
<div id="volumeBar"></div>
<div id="volume"></div>

CSS

#volumeBar {
    position: relative;
    height: 138px;
    width: 102px;
    background: url(/assets/vintage-vp/volume-container.png) no-repeat;
    top: -131px;
    left: 695px;
    z-index: 2;
overflow: hidden;
}

#volume {
    width: 36px;
    height: 79px;
    position: absolute;
    background: url(/assets/vintage-vp/volume.jpg) no-repeat black;
top: 116px;
    left: 735px;
    z-index: 1;
}

jQuery

var volumeDrag = false;
$('#volumeBar').on('mousedown', function(e) {
    volumeDrag = true;
    video[0].muted = false;
    updateVolume(e.pageY);
});
$(document).on('mouseup', function(e) {
    if(volumeDrag) {
        volumeDrag = false;
        updateVolume(e.pageY);
    }
});
$(document).on('mousemove', function(e) {
    if(volumeDrag) {
        updateVolume(e.pageY);
    }
});
var updateVolume = function(y, vol) {
    var volume = $('#volumeBar');
    var percentage;
    //if only volume have specificed
    //then direct update volume
    if(vol) {
        percentage = vol * 100;
    }
    else {
        var position = y - volume.offset().top;
        percentage = 100 * position / volume.height();
    }

    if(percentage > 100) {
        percentage = 100;
    }
    if(percentage < 0) {
        percentage = 0;
    }

    //update video volume

    video[0].volume = percentage / 100;

    //change sound icon based on volume

    var roundPixels = Math.round((video[0].volume*10))*-79;
    $('#volume').css({backgroundPosition: '0 ' +roundPixels+'px'}); 

我不想为此使用 jQuery UI 滑块。我有一种感觉,这只是一些简单的逻辑。谢谢!

4

1 回答 1

4

不会改变:

percentage = 100 * position / volume.height();

percentage = 100 - (100 * position / volume.height());

做吗?

于 2012-04-10T17:21:20.410 回答